Skip to content

Instantly share code, notes, and snippets.

@kamescg
Last active January 4, 2020 16:13
Show Gist options
  • Save kamescg/256757a241be4939cd3f93372c19abda to your computer and use it in GitHub Desktop.
Save kamescg/256757a241be4939cd3f93372c19abda to your computer and use it in GitHub Desktop.
codefund-api
import {useEffect, useState, useReducer} from 'react';
const dataFetchReducer = (state, action) => {
switch (action.type) {
case 'FETCH_INIT':
return {
...state,
isLoading: true,
isError: false
};
case 'FETCH_SUCCESS':
return {
...state,
isLoading: false,
isError: false,
data: action.payload,
};
case 'FETCH_FAILURE':
return {
...state,
isLoading: false,
isError: true,
};
default:
throw new Error();
}
};
const useCodeFundAd = (id) => {
/* --- State --- */
const [apiUrl] = useState(`https://app.codefund.io/properties/${id}/funder.json`);
/* --- Reducer --- */
const [state, dispatch] = useReducer(dataFetchReducer, {
isLoading: false,
isError: false,
data: undefined,
});
/* --- Effect --- */
useEffect(() => {
let didCancel = false;
const fetchData = async () => {
dispatch({type: 'FETCH_INIT'});
try {
const result = await fetch(url);
if (!didCancel) {
dispatch({type: 'FETCH_SUCCESS', payload: result.data});
}
} catch (error) {
if (!didCancel) {
dispatch({type: 'FETCH_FAILURE'});
}
}
};
fetchData();
return () => {
didCancel = true;
};
}, [url]);
return [state, setUrl];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment