..have a page where I show the inventories of some cards in a box of a set of cards. I can have multiple boxes of the same set, and every time I want to navigate to another box of the same set, the inventory quantities of, let's say, box 1, show up in box 2, even though they have different inventories. This happens unless I refresh the page, then the inventories of the box 2 show properly.
My code looks like this:
CardsBox.js:
// Here I show the cards, alongside their inventories, it recieves a list of cards as a parameter
import useInventoryItemsForCards from '../../hooks/Inventory/useInventoryItemsForCards';
export default function CardsBox({ cards }) {
const { isLoading, isError, error, data } = useInventoryItemsForCards(cards.map((card) => card != null && card._id));
return (
...
);
}
useInventoryItemsForCards.js:
// Here I retrieve the inventories of the cards from a MongoDB database
import { getToken } from '../../tokens/getToken';
import { basePath } from '../../config/basePath';
import { getTokenAuthHeaders } from '../../functions/sharedHeaders';
import { useParams } from 'react-router-dom';
import { useQuery } from 'react-query';
async function getInventoryItemsForCardsInBox(boxID) {
const token = await getToken();
const response = await fetch(`${basePath}/inventory/box/${boxID}`, {
method: 'GET',
headers: getTokenAuthHeaders(token)
});
return response.json();
}
export default function useInventoryItemsForCards(cards) {
const { boxID } = useParams();
return useQuery(['inventory', ...cards], () => {
if (boxID != null) {
return getInventoryItemsForCardsInBox(boxID);
} else {
throw Error('No box id');
}
});
}
I had a theory of invalidating the queries every time I fetch the inventories, however, this approach makes the page not show the list of cards at all.
