In my app I need to get products base on selected category. I decided to use RTK Query. To get data base on category I need firstly pass the category to RTK hook and then use it in slice to access a specific doc from firestore collection. The problem is that i need to pass it only once in Categories hook call and then access data in other components without the need of passing category to other hook call again, but it doesn’t work like expected.
Here is what I mean:
Categories:
const { data, isLoading } = useFetchProductsQuery("category");
console.log(data) // {data}
SpecialOffers:
const { data, isLoading } = useFetchProductsQuery();
console.log(data) // undefined
My current code:
Slice:
export const firestoreApi = createApi({
reducerPath: "firestoreApi",
baseQuery: fakeBaseQuery(),
tagTypes: ["Product"],
endpoints: (builder) => ({
fetchProducts: builder.query<any, void>({
async queryFn(category: any) {
try {
const ref = doc(db, "products", category);
const docSnap = await getDoc(ref);
let products: any = null;
products = docSnap.exists() && docSnap.data();
return { data: products };
} catch (error: any) {
console.error(error.message);
return { error: error.message };
}
},
}),
}),
});
HomePage:
export const HomePage = () => {
const [selectedCategory, setSelectedCategory] = useState("vegetables");
const { data, isLoading } = useFetchProductsQuery(selectedCategory);
return (
<Box
<Categories
selectedCategory={selectedCategory}
setSelectedCategory={setSelectedCategory}
/>
<ExclusiveOffers products={data} loading={isLoading} />
</Box>
);
};
So as I showed above I can select category in Categories and then pass it to hook after that pass data and access it in ExclusiveOffers. It could work but I need to use this data in other pages components too. How to handle?