Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const useDataApi = (initialUrl, initialData) => {
- const [url, setUrl] = useState(initialUrl);
- const [state, dispatch] = useReducer(dataFetchReducer, {
- isLoading: false,
- isError: false,
- data: initialData,
- });
- useEffect(() => {
- let didCancel = false;
- const fetchData = async () => {
- dispatch({ type: 'FETCH_INIT' });
- try {
- const result = await axios(url);
- if (!didCancel) {
- dispatch({ type: 'FETCH_SUCCESS', payload: result.data });
- }
- } catch (error) {
- if (!didCancel) {
- dispatch({ type: 'FETCH_FAILURE' });
- }
- }
- };
- fetchData();
- return () => {
- didCancel = true;
- };
- }, [url]);
- const doFetch = url => {
- setUrl(url);
- };
- return { ...state, doFetch };
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement