I'm pretty sure that I don't use correctly useReducer there is an example :
**//My array with some items**
const items = [
{
id: 0,
title: "Cidre Doux",
img:
"img",
type: "doux",
},
{
id: 1,
title: "Cidre demi-doux",
img:
"img",
type: "demi-doux",
},
]
**//UseState for passing category in dispatch**
const [categoryItem, setCategoryItem] = useState("");
**//useReducer**
const [state, dispatch] = useReducer(reducer, items);
function reducer(state, action) {
switch (action.type) {
case "all":
return [...items];
case categoryItem:
return items.map((item) =>
item.type === categoryItem ? { ...item } : null
);
default:
throw new Error();
}
}
**//function onClick**
const dispatchCategory = (category) => {
setCategoryItem(category);
dispatch({ type: category });
};
{...}
//Return
<button onClick={() => { dispatchCategory("doux");}}> Doux </button>
{...}
//My map
{state.map((item) => {
if (item != null) {
return <ShopCardItem key={item.id} {...item} />;
} else {
return "";
}
})}
In my reducer I use items and not the state because i have severals button for finding some category objets. If i use the state i can't get all items after clicking on a button.
There is an exemple if i use state in the function reducer:
Step: one, click on "all" => all items,
Step: two, click on "doux" => doux items,
Step :three, click on "all" again, only get doux items.
How can i resolve this problem ?
Ty very much !