Summarize the Problem
Goal
I am attempting to create a cart feature for my Shop Inventory project. This cart will basically contain a list of product ids and eventually allow a user to see all of the items in this ‘cart’. Once the user feels like they have added all of the products they’d like to purchase to their cart, they will have a button within the cart page to purchase all products in the cart.
Ideally, I will store a list of product ids in local storage, and once the user navigates to a certain route, I will grab the list from local storage using JSON.parse/JSON.stringify and implement the feature accordingly (Putting the products ids into a state variable called products). It seems to be working fine except for a bit of debugging code I put in place.
Expected VS Actual
I have put this debugging code inside of my component to show me the list of products that have been grabbed from local storage.
{products.map((product) => { <h2>{product}</h2>; }) }
However, whenever I load the page the only content I see is more debugging content like “Hello World” I put above it. What I expected to see when I loaded the page was a list of ids that corresponded to the products put into the cart. I know that it had at least one product inside of the ‘products’ state variable by looking into the react dev tools.
Error Messages
There are no error messages.
Describe what you’ve tried
Debugging attempts
React Dev Tools
I was able to confirm that even though the state variable list isn’t being displayed, the state variable itself is getting updated. I was able to verify this with the React Dev Tools.
VS Debugger
I also attempted to look through the debugger before and after the state had been set. The array I set it to seems to be correct:
I noticed that after going through quite a bit of the internal workings of React it came back to my code inside of useEffect. And when it did the products state variable was updated correctly. However, in the next few steps I took with the debugger, it didn’t seem to go back to my visual part to re-render it.
Stack Overflow
I have searched through some Stack Overflow questions that popped up while asking this question. I believe the closest question is this one which hasn’t been answered yet. Some of them are troubles with working with child components and directly accessing the state variable instead of using set both of which I am not doing. For the child issues, the major one I looked at was this one. For the directly accessing this is the major one.
Show some code
Cart.js
Using a functional react component, I have a ‘products’ state variable that I attempt to populate in the useEffect hook with a certain key in local storage. Below is my Cart component. You may notice there is also another state variable called ‘addingResource’ which is used to indicate if the Cart component has been created to add a resource to the cart or to simply display it. As you can see as well the addingResource state variable gets updated in the useEffect hook. I’m not entirely sure if that is possibly what is affecting the products state variable, but I figured I would note it here in case it is. Once again the main problem is that the products map function inside of the return statement does not show any items, even after the products state variable appears to be updated.
function Cart(props) { const [products, setProducts] = React.useState([]); const [addingResource, setAddingResource] = React.useState(false); const REACT_APP_CART_TOKEN_NAME = process.env.REACT_APP_CART_TOKEN_NAME; // Ensures that addingResource is updated to true if needed React.useEffect(() => { if (props.match && addingResource === false) { setAddingResource(true); } const stringVersion = window.localStorage.getItem( REACT_APP_CART_TOKEN_NAME ); let productIdsList = []; if (stringVersion) { productIdsList = JSON.parse(stringVersion); console.log("test"); } if (props.match) { productIdsList.push(props.match.params.id); window.localStorage.setItem( REACT_APP_CART_TOKEN_NAME, JSON.stringify(productIdsList) ); } alert("Updating Products"); if (!products) { setProducts(productIdsList); } }, []); // TODO: Read the products key from the local storage return ( <> <h1>Match: {`${addingResource}`}</h1> {products && products.map((product) => { <h2>{product}</h2>; })} </> ); }
Local Storage ‘Cart’ Token
Additionally, the ‘cart’ local storage token that is being accessed in this component has this structure:
[ '5fccb14ed0822f25ec5cee63' ]
Finishing Remarks
This is a recreated question from my originally closed question you can find here. I believe the reason it was closed is that I was having problems submitting my question. There appeared to be a section of code that stack overflow said was invalid. I had looked through all of the code segments I had put in and none of them seemed off. I even tried formatting the spacing in a text editor and pasting it over a few times to make sure it had the right spacing. I even removed all of the code snippets and tried to submit it that way. However, it still told me there was an error somewhere in my post. I then tried to use the process of elimination to resolve this issue by slowly removing sections of my post and trying to submit it. The problem this caused was that my initial posting had only a slight portion of the original post. I was trying to quickly find the error and fill in the rest of the information. I was able to eventually able to find the section of text near my “React Dev Tools” paragraph that was causing this error. After resolving this error, I was able to submit my post in its complete form. Unfortunately, it seems that my question was closed and even after adding some additional details to my original lengthy post and putting a section is asking the person who closed the question to review it again and message me if anything was wrong, it remained closed for nearly a week. Because of this, I decided to make a new post ensuring all of my original post’s content was available from the first version.
I greatly appreciate any help and hope to resolve this issue for me and those in the future that come across this. Thank you!
Advertisement
Answer
Your useEffect looks ok. But you need to return a value inside your map function, else it won’t display anything :
return ( <> {products.map(product => <h2>{product}</h2>)} </> );
When you remove the braces around the content of an arrow function, it is considered as the returned value. Else, you can simply write () => { return <>blabla</> });