Created
September 5, 2019 15:38
-
-
Save tgroshon/9cc2c098bb5bf8cdfc5c2ca2ea3b9e13 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment