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
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:
Instead of conditionally using the
useGetCatalogueDataByIdQuery
, just add a second parameter which conditionally executes its logic.In the
useGetCatalogueDataByIdQuery
check theskip
value and execute the logic depend on it.