1.8 KiB
1.8 KiB
up:: Boilerplate Code X:: JavaScript tags:: #boilerplate
React Query Axios Hook Boilerplate
This is boilerplate for a basic Login react query and axios hook function
Define Types
type LoginErrorMessage = { message: string };
type LoginError = AxiosError<LoginErrorMessage, any>;
type LoginPayload = { email: string; password: string };
Define function
We define a basic function which will return our mutation return result
export default function useLogin() {
return useMutation();
}
Add the type definitions to the useMutation function call so they can propogate throughout the implimentation
useMutation<User, LoginError, LoginPayload>()
Now, the useMutation function takes 3 arguments:
- cache key
- async function used for making the fetch request
- properties object
useMutation<User, LoginError, LoginPayload>(
"login",
async () => {},
{
onSuccess,
onError,
...rest
}
)
When using useQuery
and not useMutation
, the cache key can be an array for more specificity creating the cache. When using useMutation, its almost useless. For example:
useMutation: "login"
useQuery: ['login', someID]
In the async function is where we define our axios request, like so:
async (payload) => {
const { data } = await axios.post<User>("/api/login", {
email: payload.email,
password: payload.password,
})
return data;
},
Assign login to the success
and failure
properties and we're good to go with a basic hook:
{
onSuccess: (data) => console.log('success'),
onError: (error) => console.error("error")
}