Friday, July 11, 2025
HomeJavaScriptMastering React's useReducer Hook: State Administration Information

Mastering React’s useReducer Hook: State Administration Information


1 const reducer = (state, motion) => {

2 swap (motion.sort) {

3 case "loading":

4 return { ...state, loading: true, error: null };

5 case "success":

6 return { ...state, loading: false, information: motion.information };

7 case "error":

8 return { ...state, loading: false, error: motion.error };

9 default:

10 return state;

11 }

12 };

13

14 const FetchData = () => {

15 const [state, dispatch] = useReducer(reducer, { information: null, loading: false, error: null });

16

17 useEffect(() => {

18 dispatch({ sort: "loading" });

19 fetch("https://api.instance.com/information")

20 .then(res => res.json())

21 .then(information => dispatch({ sort: "success", information }))

22 .catch(error => dispatch({ sort: "error", error }));

23 }, []);

24

25 if (state.loading) return <p>Loading...</p>;

26 if (state.error) return <p>Error: {state.error}</p>;

27 return <pre>{JSON.stringify(state.information, null, 2)}</pre>;

28 };

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments