Skip to content

Instantly share code, notes, and snippets.

@tgroshon
Created September 5, 2019 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tgroshon/9cc2c098bb5bf8cdfc5c2ca2ea3b9e13 to your computer and use it in GitHub Desktop.
Save tgroshon/9cc2c098bb5bf8cdfc5c2ca2ea3b9e13 to your computer and use it in GitHub Desktop.
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