0

I'm trying to use error / isError to validate if the request failed, but it is always undefined.

This is my service (I set the URL to: 'non_exists_url')

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import {
  ICompanyDeleteRequest,
  ICompanyDeleteResponse
} from '../../interfaces/companies.interface'
import { RootState } from '../redux/store'

export const companyApi = createApi({
  reducerPath: 'companyApi',
  baseQuery: fetchBaseQuery({
    baseUrl: 'http://localhost:1000/v1/',
    prepareHeaders: (headers, { getState }) => {
      const token = (getState() as RootState).authReducer.token
      if (token) {
        headers.set('authorization', `Bearer ${token}`)
      }
      return headers
    },
  }),
  endpoints: (builder) => ({
    deleteCompany: builder.query<ICompanyDeleteResponse, ICompanyDeleteRequest>({
      query: ({ companyId }) => ({
        url: `non_exists_url`,
        method: 'DELETE',
        headers: {
          'X-CompanyId': companyId,
        },
      }),
    })
  }),
})

export const { useDeleteCompanyQuery } = companyApi

And this is inside the component:

import styles from './deleteCompany.module.scss'
import { FC, useEffect, useState } from 'react'

export const DeleteCompany: FC = () => {

  const companyId = 1
  const { data, error, isError } = useDeleteCompanyQuery(companyId)

  useEffect(() => {
    console.log('data', data)
    console.log('error', error)
    console.log('isError ', isError )
  }, [data, error, isError ])

  return (
    <div>
      Some text
    </div>
  )
}

In developer tools network I see 404 error But in the console isError and error are undefined

Any idea what I'm missing ?

Israel
  • 445
  • 2
  • 5
  • 15
  • 2
    Did you wrap the api in your reducer? I once had similar issue and it was because I forgot to add into my rootReducer – user14459580 Dec 03 '21 at 19:49
  • Yes I wrapped it. – Israel Dec 03 '21 at 19:52
  • I think it is related to the fact that 404 return HTML, and RTK try to parse it and stuck. – Israel Dec 03 '21 at 19:59
  • try add `responseHandler: (response) => response.text()` under your query. If this doesn't work I suggest you to post this issue on the RTKQ github page, there you can get a faster and more accurate response – user14459580 Dec 03 '21 at 20:05
  • Thanks, I added this: ``` responseHandler: (response: Response) => { console.log('response', response) return new Promise(async (resolve) => resolve(await response.text())) }, ``` And I can see in the response the response.status === 404, but still does not get it with the hook – Israel Dec 03 '21 at 20:17
  • yea interesting, Id just go ahead and post on the github. Also I realized that the parameter you pass in to your query is a number, but in the query you specified an object, in this case you only have 1 param, so I would directly declare it as `query: (companyID) => ({})` – user14459580 Dec 03 '21 at 22:03

1 Answers1

0

I found out that I used query instead mutation for the delete operation. Query is expecting to get JSON / text / or callback function as response, but error 404 return HTML that can not be parsed as JSON.

I ended up changing to mutation like this:

In the service file:

deleteCompany: builder.mutation<ICompanyDeleteResponse, ICompanyDeleteRequest>({
      query: ({ companyId }) => ({
        url: `PreventDelete/companies`,
        method: 'DELETE',
      }),
    })

Using it in component:

  const [deleteCompany, { data, error, isLoading }] = useDeleteCompanyMutation()

useEffect(() => {
    console.log('data', data)
    console.log('error', error)
    console.log('isLoading', isLoading)
    if (!error && data) {
      NotificationManager.success('Deleting company success', `Company ${company.id} deleted successfully`)
    } else if (error) {
      NotificationManager.error('Delete company error', `Error deleting company ${company.id}, details: ${data}`)
    }
  }, [data, error, isLoading])

Israel
  • 445
  • 2
  • 5
  • 15