triston-notes/Cards/dev/React Query Axios Hook Boilerplate.md
2023-10-21 18:52:54 -05:00

1.8 KiB

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

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:

  1. cache key
  2. async function used for making the fetch request
  3. 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")
}