Last active
January 4, 2020 16:13
-
-
Save kamescg/256757a241be4939cd3f93372c19abda to your computer and use it in GitHub Desktop.
codefund-api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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