0

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?

1 Answer 1

1

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
            }
        )
    }
Sign up to request clarification or add additional context in comments.

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.