Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import axios from "axios";
- // Using `useState()` to manage individual pieces
- function ComponentWithPlainState({ coursenum }) {
- let [loading, setLoading] = useState(false);
- let [data, setData] = useState();
- let [errors, setErrors] = useState();
- useEffect(() => {
- setLoading(true);
- setErrors(null);
- axios
- .get(`/some/url/${coursenum}`)
- .then(resp => {
- setData(resp.data);
- })
- .catch(err => {
- setErrors(err);
- })
- .finally(() => {
- setLoading(false);
- });
- }, [axios, coursenum]);
- // do things with loading, data, and errors
- }
- // Using `useReducer()` to manage individual pieces
- function reducer(state, action) {
- switch (action.type) {
- case "START":
- return { ...state, loading: true, errors: null };
- case "SUCCESS":
- return { ...state, loading: false, data: action.data };
- case "FAIL":
- return { ...state, loading: false, errors: action.errors };
- }
- }
- const INIT_STATE = {
- loading: false,
- errors: null,
- data: null
- };
- function ComponentWithReducer({ coursenum }) {
- let [{ loading, data, errors }, dispatch] = useReducer(reducer, INIT_STATE);
- useEffect(() => {
- dispatch({ type: "START" });
- axios
- .get(`/some/url/${coursenum}`)
- .then(resp => {
- dispatch({ type: "SUCCESS", data: resp.data });
- })
- .catch(err => {
- dispatch({ type: "FAIL", errors: err });
- });
- }, [axios, coursenum]);
- // do things with loading, data, and errors
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement