`
I am receving a cat prop and want to fetch data from api whenever cat is changed
using RTK query but getting error as "React Hook "useGetProductsQuery" cannot be called inside a callback".
Please assist on how to make a RTK query whenver cat is changed
const Products = ({cat,filter,sort}) => {
const [products, setproducts] = useState([])
const [filters, setFilters] = useState([])
useEffect(()=>{
const {data,isError,isLoading}=useGetProductsQuery()
console.log(data,isError,isLoading)
},[cat])
}
import { createApi, fetchBaseQuery }
from'@reduxjs/toolkit/query/react';
const baseUrl=process.env.REACT_APP_ECOMMERCE_API_URL
const createRequest = (url) => ({ url });
export const ecommApi = createApi({
reducerPath: 'ecommApi',
baseQuery: fetchBaseQuery({baseUrl}),
endpoints: (builder) => ({
getProducts: builder.query({
query: () => createRequest("/api/v1/products")
}),
})
})
export const{useGetProductsQuery}=ecommApi;
`
CodePudding user response:
Why not just pass cat
as an argument to the useQuery
hook without the useEffect
?
That will make a new request every time cat
changes.
const {data,isError,isLoading}=useGetProductsQuery(cat)
CodePudding user response:
As an addition to phry's answer:
If "cat" might be undefined use the skip
parameter for conditional fetching:
const {data,isError,isLoading} = useGetProductsQuery(cat, {skip: !cat})
See https://redux-toolkit.js.org/rtk-query/usage/conditional-fetching