Last active
September 26, 2019 20:53
-
-
Save ZakKa89/c7f2b6d0d80cd3ba2da7a333c46bddbb to your computer and use it in GitHub Desktop.
useApi hook
This file contains hidden or 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 { ErrorType } from '~/core/api'; | |
type ReturnType<DataType> = [ | |
{ | |
data: DataType; | |
loading: boolean; | |
isSuccess: boolean; | |
errorMessage: ErrorType['message']; | |
errorData: ErrorType['data']; | |
}, | |
() => {} // <-- wip | |
]; | |
export function useApi<T>(apiFunction, initialDataValue): ReturnType<T> { | |
const [response, setResponse] = React.useState({ | |
data: initialDataValue, | |
errorMessage: null, | |
errorData: null, | |
isFetching: false, | |
isSuccess: false, | |
}); | |
const fetchData = React.useCallback(async () => { | |
setResponse(prevState => ({ | |
...prevState, | |
loading: true, | |
})); | |
try { | |
const apiData = await apiFunction(); | |
setResponse({ | |
data: apiData, | |
isFetching: false, | |
errorMessage: null, | |
errorData: null, | |
isSuccess: true, | |
}); | |
} catch (error) { | |
setResponse({ | |
data: null, | |
isFetching: false, | |
errorMessage: error.message, | |
errorData: error.data, | |
isSuccess: false, | |
}); | |
} | |
}, [apiFunction]); | |
return [response, fetchData]; | |
} |
This file contains hidden or 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 { useApi} from "~/hooks/useApi" | |
const UsersPage = () => { | |
type UsersType = { | |
firstName: string; | |
lastName: string; | |
} | |
const [usersResponse, getUsers] = useApi<UsersType[]>(fetchUsers, []); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment