I faced a problem when using redux. I have two arrays with objects in it, initially they are empty. One of these arrays contains objects that are marked as 'favorite' - by user.
const INITIAL_STATE = {
favorites: [],
recipes: [],
};
My reducer for adding item:
const reducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case "TOGGLE_FAVORITES":
if (!state.favorites.includes(action.payload)) {
return { ...state, favorites: [...state.favorites, action.payload] };
}
return {
...state,
favorites: state.favorites.filter(
(recipe) => recipe.id !== action.payload.id
),
};
case "REMOVE_FROM_FAVORITES":
return {
...state,
favorites: state.favorites.filter(
(recipe) => recipe.id !== action.payload
),
};
case "GET_RECIPES":
return {
...state,
recipes: action.payload,
};
default:
return state;
}
};
I have this 'toggle' type for the same button if user decides to add and then remove from favorites.
The problem is When i add item to array it doesn't update right away. I mean, on first 'add' click my favorites array is empty, but when i add another item it shows that there is one item inside, and so on and so forth.
Is there a way to update state whenever i add something to show me really current state?
Checking if favorite like this:
const [isFavorite, setIsFavorite] = useState(false);
// Checking if recipe is favorite when rendered
useEffect(() => {
const checkIfIsFavorite = (id) => {
for (let i = 0; favorites.length > 1; i++) {
if (id === favorites[i].id) {
return true;
}
return false;
}
};
setIsFavorite(checkIfIsFavorite(recipe.id));
}, [favorites, recipe.id]);