Home > Enterprise >  my error object is undefined when i`m using rtk query with try/catch
my error object is undefined when i`m using rtk query with try/catch

Time:12-18

first of all i want to apologize for my title. I just dont know how to describe my problem.

I am trying to get a bad response from my server and when I try to display that my object is undefined

I have a base query methods here:

export const accountSlice = apiSlice.injectEndpoints({
    endpoints: builder => ({
        login: builder.mutation({
            query: credentials => ({
                url: 'account/login',
                method: 'POST',
                body: { ...credentials },
            })
        }),
        register: builder.mutation({
            query: credentials => ({
                url: 'account/register',
                method: 'POST',
                body: { ...credentials },
            })
        })
    })
})

My handle submit on register page ->

    const [register, { isLoading, isError }] = useRegisterMutation();

    const handleSubmit = async (e) => {
        e.preventDefault();

        try {
            const result = await register({ name, nickName, email, password }).unwrap();
            setRegisterResponse(result);
        } catch (error) {
            setRegisterResponse(error);
        }
    }

And my logic to show it. When i use console.log(registerResponse) it returnes two logs in console - first object is empty, second object with properties ->

               {
                    isError &&
                    <h2>
                        Ooops.. something went wrong:
                        {
                           console.log(registerRespnse)
                        }
                    </h2>
                }

Error in google console

CodePudding user response:

You shouldn't need to call a setRegisterResponse state setter, because that response will just be available for you:

  //                              see data and error here
  const [register, { isLoading, isError, data, error }] = useRegisterMutation();

As why it logs undefined once: first the query finishes with an error (which will rerender the component and already fill error I showed above and set isError) and then the Promise resolves and your custom code sets your response local state, which causes a second rerender (and only on the second render, response is set)

  • Related