Advertisement
Guest User

Untitled

a guest
Sep 16th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. import axios from "axios";
  2.  
  3. // Using `useState()` to manage individual pieces
  4.  
  5. function ComponentWithPlainState({ coursenum }) {
  6. let [loading, setLoading] = useState(false);
  7. let [data, setData] = useState();
  8. let [errors, setErrors] = useState();
  9. useEffect(() => {
  10. setLoading(true);
  11. setErrors(null);
  12. axios
  13. .get(`/some/url/${coursenum}`)
  14. .then(resp => {
  15. setData(resp.data);
  16. })
  17. .catch(err => {
  18. setErrors(err);
  19. })
  20. .finally(() => {
  21. setLoading(false);
  22. });
  23. }, [axios, coursenum]);
  24.  
  25. // do things with loading, data, and errors
  26. }
  27.  
  28. // Using `useReducer()` to manage individual pieces
  29.  
  30. function reducer(state, action) {
  31. switch (action.type) {
  32. case "START":
  33. return { ...state, loading: true, errors: null };
  34. case "SUCCESS":
  35. return { ...state, loading: false, data: action.data };
  36. case "FAIL":
  37. return { ...state, loading: false, errors: action.errors };
  38. }
  39. }
  40.  
  41. const INIT_STATE = {
  42. loading: false,
  43. errors: null,
  44. data: null
  45. };
  46.  
  47. function ComponentWithReducer({ coursenum }) {
  48. let [{ loading, data, errors }, dispatch] = useReducer(reducer, INIT_STATE);
  49. useEffect(() => {
  50. dispatch({ type: "START" });
  51. axios
  52. .get(`/some/url/${coursenum}`)
  53. .then(resp => {
  54. dispatch({ type: "SUCCESS", data: resp.data });
  55. })
  56. .catch(err => {
  57. dispatch({ type: "FAIL", errors: err });
  58. });
  59. }, [axios, coursenum]);
  60.  
  61. // do things with loading, data, and errors
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement