'How to complete login authentication in react by using react query mutations?

I am trying to complete login authentication of my app by using react query.

Firstly i have created mutation function by using use mutation which is,

import { useMutation } from 'react-query'
import MainApi from '../../../api/MainApi'
import { login_api } from '../../../api/ApiEndPoints'

const addLoginCredentials = (loginCredentials) => {
    return MainApi.post(login_api, {
        email_or_phone: loginCredentials.email,
        password: loginCredentials.password,
    })
}
export const useAddLoginCredentials = () => {
    return useMutation(addLoginCredentials)
}

after that i imported it to my main component. Which is,

const {
        mutate,
        isError,
        error,
        isLoading,
        isSuccess,
        status,
        data: loginData,
    } = useAddLoginCredentials()

then i wanted to pass data on the mutate properties of this, within a submit function, which is,

  onSubmit: async (values, helpers) => {
            mutate(values
        },

when i click the login button which calls the onSubmit function, it hits the api, and gets some data, when i get the data, i want to show toasters inside , isSuccess. I wrote the code for the desired outcome, which is,

if(isSuccess){
toast.success('done')
}

but it renders multiple times with my login button click. I want to show the toaster only one time, exactly after the api call done.



Solution 1:[1]

The fact that is shows multiple toast points to the fact you should not use isSuccess flag of mutations/queries to handle toasts because if the component rerenders for unrelated reasons to the mutation or query, it will show a new toast. Instead, you need to use the onSuccess callback that only fires when success happens.

onSubmit: async (values, helpers) => {
  mutate(values, { onSuccess: () => toast.success('done') })
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jakub Kotrs