0

I have a basic API built in Laravel and a React app that is running alongside it. I'm making a PUT request to update some data via React Query, which works fine and the data goes through. I was looking to extend it to handle server-side validation errors (essentially calling Formik's setErrors on them). Laravel back-end responds with a 422 error, as expected, and I can see JSON with the field errors in the Network tab. However, trying to get hold of the error object in react-query mutation's callback only gives me text content:

VM3965 update-form.tsx:61 Error: Request failed with status code 422
    at createError (createError.js?770c:16:1)
    at settle (settle.js?8768:17:1)
    at XMLHttpRequest.onloadend (xhr.js?1a5c:66:1)

I sort of expected to be able to get hold of the error object containing the JSON with validation errors here. Probably missing something obvious.

Here's what the mutation hook looks like:

export const useUpdateClient = (id: string) => {
  const queryClient = useQueryClient()

  return useMutation(
    (newClient: Client) => axios.put(`/api/clients/${id}`, newClient),
    {
      onSuccess: () => queryClient.invalidateQueries(['clients']),
    },
  )
}

and this how I call it from the component:

const updateClient = useUpdateClient(id)
const handleSubmit = (
      values: Client,
      { setErrors }: FormikHelpers<Client>,
    ) => {
      updateClient.mutate(values, {
        onSuccess: () => {
          onClose(),
          toast({
            title: 'Client updated',
            status: 'success',
          })
        },
        onError: error => console.log(error), // <<< this only prints text
      })
    }

0 Answers0