Home > Enterprise >  Problem with useMutation typisation in ReactQuery
Problem with useMutation typisation in ReactQuery

Time:07-27

I am writing simple app with authorization. User data is stored in the DB. I am using useMutation hook and axios library to send POST requests on my server during registration.

I've run out into a problem - I can't come up with a proper typisation:

    type ErrorResponse = {
        response: {
            data: {
                message: string
            }
        }
    }

    type SuccessResponse = {
        message: string
    }

    const { mutate, isError, isLoading, error } = useMutation<

        any, // <-- HERE!

        ErrorResponse,
        IUser
    >(newUser =>
        axios
            .post('http://localhost:3000/registration', newUser)
            .then(() => navigate('/login'))
    )

When I am trying to replace any with SuccessResponse type I am getting this error:

No overload matches this call.
  The last overload gave the following error.
    Argument of type '(newUser: IUser) => Promise<void | SuccessResponse>' is not assignable to parameter of type 'MutationKey'.ts(2769)

I guess it has something to do with .then(() => ... usage after axios .post() request but I am not really sure.

Is there any way to type useMutation hook in this situation properly?

CodePudding user response:

Actually, I was right about problem with .then() => ... after request in useMutation body. I removed it and used integrated option onSuccess in mutate function which I've got from the hook.

This is how my solution looks like:

    type ErrorResponse = {
        response: {
            data: {
                message: string
            }
        }
    }

    type SuccessResponse = {
        message: string
    }

    const { mutate, isError, isLoading, error } = useMutation<

        SuccessResponse, // <-- NOW EVERYTHING IS STRONGLY TYPED!

        ErrorResponse,
        IUser
    >(newUser =>
        axios.post(
            'https://nasa-apod-project-backend.herokuapp.com/registration',
            newUser
        ) // <-- REMOVED .then(() => ...)

    )

    function handleRegistration(e: React.MouseEvent<HTMLButtonElement>) {
        e.preventDefault()
        mutate(
            { password, username },
            {
                onSuccess: () => navigate('/login') // <-- USED THIS INSTEAD
            }
        )
    }
  • Related