Guest User

Untitled

a guest
Apr 18th, 2019
86
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const useDataApi = (initialUrl, initialData) => {
  2. const [url, setUrl] = useState(initialUrl);
  3.  
  4. const [state, dispatch] = useReducer(dataFetchReducer, {
  5. isLoading: false,
  6. isError: false,
  7. data: initialData,
  8. });
  9.  
  10. useEffect(() => {
  11. let didCancel = false;
  12.  
  13. const fetchData = async () => {
  14. dispatch({ type: 'FETCH_INIT' });
  15.  
  16. try {
  17. const result = await axios(url);
  18.  
  19. if (!didCancel) {
  20. dispatch({ type: 'FETCH_SUCCESS', payload: result.data });
  21. }
  22. } catch (error) {
  23. if (!didCancel) {
  24. dispatch({ type: 'FETCH_FAILURE' });
  25. }
  26. }
  27. };
  28.  
  29. fetchData();
  30.  
  31. return () => {
  32. didCancel = true;
  33. };
  34. }, [url]);
  35.  
  36. const doFetch = url => {
  37. setUrl(url);
  38. };
  39.  
  40. return { ...state, doFetch };
  41. };
RAW Paste Data