2

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.

2 Answers 2

2

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 onError lifecycle of useMutation, and maybe display a message for the user depending on which request failed.

Sign up to request clarification or add additional context in comments.

Comments

1

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;
      }
    },
  });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.