Home > Mobile >  What is the best way about send multiple query in useMutation (React-Query)
What is the best way about send multiple query in useMutation (React-Query)

Time:12-12

I developed login function use by react-query in my react app

The logic is as follows

  1. First restAPI for checking duplication Email
  2. If response data is true, send Second restAPI for sign up.

In this case, I try this way


// to declare useMutation object
let loginQuery = useMutation(checkDuple,{
    // after check duplication i'm going to sign up
    onSuccess : (res) => {
      if(res === false && warning.current !== null){
        warning.current.innerText = "Sorry, This mail is duplicatied"
      }else{
        let res = await signUp() 
      }
    }
  })

//---------------------------------------------------------------------------------
const checkDuple = async() => {                                       
    let duple = await axios.post("http://localhost:8080/join/duple",{
        id : id,
    })
}

const signUp = async() => {
    let res = await axios.post("http://localhost:8080/join/signUp",{
    id : id,
    pass : pass
  })
  console.log(res.data)
  localStorage.setItem("token", res.data)
  navigate("/todo")
}


I think, this isn't the best way, If you know of a better way than this, please advise.

CodePudding user response:

Better to have another async function that does both things.

something like

const checkDupleAndSignUp = async () => {
  await checkDuple();
  await signUp();
};

And then use that in your useMutation instead.

Other things to consider:

Maybe move the logic to set local storage and navigate to another page in the onSuccess instead.

You can also throw your own error if one or the other request fails and then check which error happened using one rror lifecycle of useMutation, and maybe display a message for the user depending on which request failed.

CodePudding user response:

You can handle both of them in a single function and in mutation just add token in localStorage and navigate

like this:

 const checkDupleAndSignUp = async () => {
    return checkDuple().then(async res => {
      if (res === false) {
        return {
          isSuccess: false,
          message: 'Sorry, This mail is duplicatied',
        };
      }
      const { data } = await signUp();
        return {
          isSuccess: true,
          data,
        };
      
    });
  };

and in mutation :

  let loginQuery = useMutation(checkDupleAndSignUp, {

    onSuccess: res => {
      if (res.isSuccess) {
        console.log(res.data);
        localStorage.setItem('token', res.data);
        navigate('/todo');
      } else if (warning.current !== null) {
        warning.current.innerText = res.message;
      }
    },
  });
  • Related