I'm trying to understand useContext with what, I thought, would be a trivial example...
I'm not putting the entire code in here but only relevant snippets, the full code is on codesandbox
I have a page with two components. On the left is a list. On the right is a container. When I click on an "add" button under my items, they appear on the component container on the right.
After that, one can click on a submit button in the list container which routes to another component with the list of items. One can remove items from there.
I'm doing all to learn how to share properties all over a React app. I have a few problems:
- When I add an element, if the name is already included. I don't want to display it ten times. Instead, I want to display it once and then show how many times it's been added next to it. I struggle to do that because of how setItemList works in here:
const addItem = useCallback((item) => {
setCounter((prev) => ({
...prev,
[item.name]: (prev[item.name] || 0) + 1
}));
setItemList((prev) => [...prev, item]);
}, []);
And that's how I add in my List component:
const addItemToItemList = (item: Item) => {
/*if (!itemList.includes(item))*/ addItem(item);
};
I commented the if statement out to be able to add an item more than once but then it appears over and over again instead of just once (with the counter next to it)
My second problem is I don't know how to access the second counter. I don't even know how to access it with a simple console.log...
Finally, at the moment, if I add the same thing three times in my list container and then submit, on the last page, when I click remove, it removes all of them at once whereas I want to delete only one obviously. I guess it's because my removeItem works with the name but I can't think of any other way to implement that...
const removeItem = useCallback(
(itemName) =>
setItemList((prev) => prev.filter((it) => it.name !== itemName)),
[]
);
Anyway, I look forward to getting some tips and hints. Enjoying the React Hooks journey so far. Thank you!