Reputation: 29
I have home component and i passing props into Product card component
{products.map((product: ProductListStoreType) => (
<ProductCard
key={product.slug}
product={product}
category={product.category}
/>
))}
</div>
Category is just string _id from mongo db
and inside the product card
export default function ProductCard({ product, category }: ProductCardProps) {
const getCategory = async () => {
const { data } = await axios.get(`/api/category/${category}`);
return data.name;
};
const { data } = useSWR('/api/category', getCategory);
console.log(data);
The problem is SWR returns the same data for every loop. the id category is unique because it is from the _id mongo DB. but SWR keeps returning the same data which is from the category _id from the first loop
awlays return the first data for every map
Upvotes: 0
Views: 1071
Reputation: 671
The first parameter of useSWR
is a unique key
identifying the request. Since the key you are passing does not change (it's always '/api/category'
), the data is not refreshed.
The key
will be as the first argument to your fetcher
, see the docs on arguments.
With these two things in mind, you could do something like this:
const getCategory = async (path) => {
const { data } = await axios.get(path);
return data.name;
};
export default function ProductCard({ product, category }: ProductCardProps) {
const { data } = useSWR(`/api/category/${category}`, getCategory);
Upvotes: 1