triston-notes/Cards/dev/React Query Axios Hook Boilerplate.md

72 lines
1.8 KiB
Markdown
Raw Permalink Normal View History

2023-10-21 23:52:54 +00:00
---
banner: "https://media.discordapp.net/attachments/1050995657797816341/1090945535948636160/Triston_hq_4k_3e3d048b-d1fe-4f91-b740-81ec88f4052f.png?width=1726&height=968"
---
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
```ts
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
```ts
export default function useLogin() {
return useMutation();
}
```
Add the type definitions to the useMutation function call so they can propogate throughout the implimentation
```ts
useMutation<User, LoginError, LoginPayload>()
```
Now, the useMutation function takes 3 arguments:
1. cache key
2. async function used for making the fetch request
3. properties object
```ts
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:
```ts
useMutation: "login"
useQuery: ['login', someID]
```
In the async function is where we define our axios request, like so:
```ts
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:
```ts
{
onSuccess: (data) => console.log('success'),
onError: (error) => console.error("error")
}
```