skip to Main Content

I have this component where i don’t want to all api unless Catalogue id exists

const GeneralInfoForm = ({ currentStep, setCurrentStep }: GeneralInfoFormValues) => {
  const user = getCurrentUser();
  const dispatch= useAppDispatch()
  // Mutation hook for adding catalogue info
  const [addCatalogueInfoMutation, { isLoading }] = useAddCatalogueInfoMutation();
  const CatalogueIdFromStore=useAppSelector((state)=>state.catalogueId.id)
  const { data} = CatalogueIdFromStore && useGetCatalogueDataByIdQuery({ catalogueId:CatalogueIdFromStore,queryParams:'' });
  console.log(data,"from general info")

but it says

React Hook "useGetCatalogueDataByIdQuery" is called conditionally. React Hooks must be called in the exact same order in every component render.eslintreact-hooks/rules-of-hooks
(alias) useGetCatalogueDataByIdQuery<UseQueryStateDefaultResult<QueryDefinition<any, BaseQueryFn<FetchArgs, BaseQueryApi, DefinitionType>, "brand" | "draftsTask" | "allEmployees", any, "baseApi">>>(arg: any, options?: (UseQuerySubscriptionOptions & UseQueryStateOptions<...>) | undefined): UseQueryHookResult<...>
import useGetCatalogueDataByIdQuery

how can i solve this problem?

2

Answers


  1. The error you’re encountering is because you’re conditionally calling the useGetCatalogueDataByIdQuery hook based on the value of CatalogueIdFromStore. React hooks must be called unconditionally, and in the same order on every render, to ensure consistent behavior and avoid bugs.

    So you can do Create a custom hook to fetch the catalogue data and then In your GeneralInfoForm component, call the custom hook:

    Login or Signup to reply.
  2. Instead of conditionally using the useGetCatalogueDataByIdQuery, just add a second parameter which conditionally executes its logic.

      const { data } = useGetCatalogueDataByIdQuery({ catalogueId: CatalogueIdFromStore, queryParams: '' }, {
        skip: !CatalogueIdFromStore
      });
    

    In the useGetCatalogueDataByIdQuery check the skip value and execute the logic depend on it.

    export const useGetCatalogueDataByIdQuery = (param1, param2) => {
      if (!param2) {
         // your logic
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search