I am working on a React application and I am using Redux to manage the state. I have the following code:
reducer.js
import { actionTypes } from "./actionsTypes";
const initialState = {
items: [],
loading: false,
error: null,
bookmarks: [],
hidden: false,
basket: [],
};
const productReducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.FETCH_PRODUCTS_BEGIN:
return {
...state,
loading: true,
error: null,
};
case actionTypes.FETCH_PRODUCTS_SUCCESS:
return {
...state,
loading: false,
items: action.payload,
};
case actionTypes.FETCH_PRODUCTS_FAILURE:
return {
...state,
loading: false,
error: action.payload,
items: [],
};
case actionTypes.ADD_TO_BOOKMARK:
return {
...state,
bookmarks: [...state.bookmarks, action.payload],
};
case actionTypes.ADD_TO_BASKET:
return {
...state,
basket: [...state.basket, action.payload],
};
case actionTypes.TOGGLE_HIDDEN:
return {
...state,
hidden: !state.hidden,
};
default:
return state;
}
};
export default productReducer;
actions.js
import axios from "axios";
import { actionTypes } from "./actionsTypes";
..
...
...
export const addToBookmarks = (item) => ({
type: actionTypes.ADD_TO_BOOKMARK,
payload: item,
});
export const addToBasket = (product) => ({
type: actionTypes.ADD_TO_BASKET,
payload: product,
});
axios.defaults.baseURL = "https://fakestoreapi.com";
export const fetchProducts = () => {
return (dispatch) => {
dispatch(fetchProductsBegin());
try {
return axios
.get("https://fakestoreapi.com/Products")
.then(({ data }) => dispatch(fetchProductsSuccess(data)));
} catch (error) {
dispatch(fetchProductsFailure(error));
}
};
};
selectors.js
import { createSelector } from "reselect";
export const selectItems = (state) => state.products;
export const selectBookmarksProducts = createSelector(
[selectItems],
(shop) => shop.bookmarks
);
For my reducer function, the initial state ( items ) is retrieved data from an api.
Product.js
const Product = ({ product, toggleHidden, addToBookmarks, addToBasket }) => {
const { title, category, description, image, price } = product || {};
return (
<div className="relative">
....
.....
<HeartIcon
className={`absolute top-2 right-4 w-8 cursor-pointer ${
bookmark ? "text-red-500" : "text-gray-500"
}`}
onClick={() => addToBookmarks(product)}
/>
<CustomButton onClick={() => addToBasket(product)}>
Add to Basket
</CustomButton>
</div>
);
};
export const mapDispatchToProps = (dispatch) => ({
addToBookmarks: (item) => dispatch(addToBookmarks(item)),
toggleHidden: () => dispatch(toggleHidden()),
addToBasket: (item) => dispatch(addToBasket(item)),
});
export default connect(null, mapDispatchToProps)(Product);
Note : I dispatched an action addToBookmarks and I passed product as an object
After that, I want to get the bookmarks products in the bookmarksPage
I don't know why I got this error TypeError: state.bookmarks is not iterable
Please can anyone help