Use mutateAsync result to update token on Button click

77 Views Asked by At

I am trying to use useMutation() from react-query the best way I can, but I struggle.

My problem is that I want to post a code and a login to my backend server when I click on a button. On sucess, I should get a token. And I want to use setToken from my AuthContext and navigte to the profile page "/profile".

Here is what I tried :

import { useState } from 'react';

import { Button } from './Button';
import {Navigate, useNavigate} from 'react-router-dom';
import {api} from '@/utils/api';
import {useMutation} from 'react-query';
import {useAuth} from '@/hooks/useAuth';

const loginWithTwoFaCode = async ({code, login} : {code: string, login: string | undefined}) => {
      console.log('[loginWithTwoFaCode]', code, login)
      const json = await api.post('auth/2fa/login', { json: { twoFACode: code, login: login } }).json();
      console.log(json)
      return json;
}

export const TwoFaLoginInput = (props: any) => {
  const [code, setCode] = useState('');
  const { login, setToken } = useAuth();

  const handleCodeChange = (event: any) => {
    setCode(event.target.value);
  };

  const handleSubmit = () => {
  };

  const navigate = useNavigate();

  const mutation = useMutation({mutationFn: loginWithTwoFaCode})

  return (
    <>
    <form onSubmit={handleSubmit} className="flex flex-col items-center">
      <input type="test" name="2FAcode" onChange={handleCodeChange} />
    </form>
      <Button size="small" type="primary" onClick={() => mutation.mutateAsync({code: code, login: login}).then(() => {console.log('mutation =', mutation)})}>
        Submit
      </Button>
    </>
  );
};

The console gives me a data = undefined :

mutation = 
Object { context: undefined, data: undefined, error: null, failureCount: 0, isPaused: false, status: "idle", variables: undefined, isLoading: false, isSuccess: false, isError: false, … }

How could I use the return token to set it with setToken in my auth context ?

I am also probably doing things the wrong way, so if you have a better solution to do this post request on click, I am all ears.

Thanks

2

There are 2 best solutions below

0
On BEST ANSWER

Finally managed to do something with the result of the post request, thanks to the documentation :

  const mutation = useMutation({
    mutationFn: loginWithTwoFaCode,     
    onSuccess: data => {
      if (data.token) {
        setToken(data.token)
        console.log("Setting token to ", data.token)
      }
        navigate("/");
    },
  })

Source: https://tanstack.com/query/v4/docs/react/guides/updates-from-mutation-responses

Now I need to figure how to fix the type error on data ('data' is of type 'unknown'.ts(18046))

0
On

I advice set side effect into function. That recommendation in 5 version. I write link later (sorry, now cant find it).