Skip to content

Instantly share code, notes, and snippets.

@ZakKa89
Last active September 26, 2019 20:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZakKa89/c7f2b6d0d80cd3ba2da7a333c46bddbb to your computer and use it in GitHub Desktop.
Save ZakKa89/c7f2b6d0d80cd3ba2da7a333c46bddbb to your computer and use it in GitHub Desktop.
useApi hook
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];
}
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