Advertisement
Guest User

Untitled

a guest
Apr 25th, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. import {useContext, useEffect, useReducer} from "react"
  2.  
  3. import FetcherContext from "~/components/fetcher.js"
  4. import UserContext from "~/components/user.js"
  5.  
  6. const reducer = (state, action) => {
  7. const {type, payload} = action
  8. switch (type) {
  9. case "SET_URL":
  10. case "FETCH_INIT":
  11. return {
  12. ...state,
  13. ...(payload && payload.url && {url: payload.url}),
  14. data: null,
  15. loading: true,
  16. error: null,
  17. }
  18. case "FETCH_SUCCESS":
  19. return {
  20. ...state,
  21. data: payload.data,
  22. loading: false,
  23. error: null,
  24. }
  25. case "FETCH_FAILURE":
  26. return {
  27. ...state,
  28. data: null,
  29. loading: false,
  30. error: payload.error,
  31. }
  32. }
  33. }
  34.  
  35. const useFetcher = (url, options) => {
  36. let initialState = {
  37. url: url || null,
  38. loading: false,
  39. data: null,
  40. error: null,
  41. }
  42. const [state, dispatch] = useReducer(reducer, initialState)
  43. const {api, options: fetchOptions} = useContext(FetcherContext)
  44. const userContext = useContext(UserContext)
  45.  
  46. const setURL = url => dispatch({type: "SET_URL", payload: {url}})
  47. const setURLAndFetch = url => {
  48. dispatch({type: "SET_URL", payload: {url}})
  49. doFetch()
  50. }
  51.  
  52. const doFetch = async (url, options) => {
  53. dispatch({type: "FETCH_INIT", ...(url && {payload: {url}})})
  54. try {
  55. const finalUrl = url ? url : state.url
  56. const res = await fetch(`${api}${finalUrl}`, {
  57. ...fetchOptions,
  58. ...options,
  59. })
  60. for (const [header, value] of res.headers) {
  61. if (header.toLowerCase() === "x-auth") {
  62. if (value !== "") {
  63. const error = "AUTH_REQUIRED"
  64. dispatch({type: "FETCH_FAILURE", payload: {error}})
  65. userContext.setAuthFields(value.split(";"), finalUrl)
  66. return
  67. }
  68. }
  69. if (header.toLowerCase() === "x-authlastresult") {
  70. if (value === "true") {
  71. userContext.removeAuthFields()
  72. }
  73. }
  74. }
  75. const data = await res.json()
  76. dispatch({type: "FETCH_SUCCESS", payload: {data}})
  77. } catch (error) {
  78. dispatch({type: "FETCH_FAILURE", payload: {error}})
  79. }
  80. }
  81.  
  82. useEffect(() => {
  83. if (url) {
  84. doFetch()
  85. }
  86. }, [url, options])
  87.  
  88. return {...state, setURL, setURLAndFetch, doFetch}
  89. }
  90.  
  91. export default useFetcher
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement