The problem with updating data without auto-updating the page
please help with this, I provide the code below
if possible, tell me what I’m doing wrong and how to avoid it in the future
frontend
async getFavoriteUser(userId: string){
try {
const response = await MarketService.getFavoriteProducts(userId);
const favorites = response.data
return favorites;
} catch (error) {
}
}
async deleteFavorite(favoriteId: number, userId: string){
try {
await MarketService.deleteFavorite(favoriteId, userId)
const favorites = await this.getFavoriteUser(userId);
console.log(favorites);
} catch (error) {
console.error(error);
}
}
backend
product controller
async getFavoriteProducts(userId) {
try {
const currentUser = await UserModel.findById(userId);
const favoriteProductIds = currentUser.favorites || [];
const favoriteProducts = await ProductModel.find({ _id: { $in: favoriteProductIds } });
return favoriteProducts;
} catch (error) {
throw error;
}
}
async deleteFavorite(favoriteId, userId) {
try{
const currentUser = await UserModel.findById(userId);
const favorites = currentUser.favorites || [];
favorites.splice(favoriteId, 1);
currentUser.favorites = favorites;
await currentUser.save();
return favorites
} catch (error) {
}
}
I tried to change it useEffect
useEffect(() => {
store.getFavoriteUser(store.user.id)
.then((favoritesData) => {
setFavoriteProducts(favoritesData.favoriteProducts);
})
.catch((error) => {
console.error("Ошибка при получении избранных товаров:", error);
});
}, [store]);
here’s how it is output
<TabPanel value={value} index={2}>
Избранные товары
<Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 2 }}>
{favoriteProducts.map((product) => (
<Card key={product._id} sx={{ width: 305, height: 450 }}>
{product.name}
<Button size="small" variant="contained" color='error' onClick={() => handleDeleteFavorites(favoriteProducts.indexOf(product))}>
Удалить
</Button>
</Card>
))}
</Box>
</TabPanel>