Home > Mobile >  How to solve undefined error when trying to access a nested array in a React state variable?
How to solve undefined error when trying to access a nested array in a React state variable?

Time:02-20

I am trying to build a form in which you can dynamically add fields and subfields. As an example, my form looks like this:

    Store information:
      Name
      Items inventory: [] (this is the nested array part,
            you press a button and can add another item to the inventory)
            ***Buttons to add more items to this store***

      ***Buttons to add more stores***
    

The code I am using to achieve this looks like this:

function StoreForm() {
  const [storeInputs, setStoreInputs] = useState([
    { storeName: "", items: [{ itemName: "" }] },
  ]);
   ///...
    
    return (
        {storeInputs.map(store,index) => 
        {
            //input data here
            
            {storeInputs.items.map(item,i) => 
                {
                    //This is where it throws the undefined error
                    //do something
                }
            }
        }
    )
   
}

But I am getting an error when I try to access the nested array of items using map. I tried it with an empty array, as well as with the code that I have posted above.

I can't for the life of me figure out what I am doing wrong. The closest explanation I have is that the state variable initializes the array in another pass of the renderer, but even if I do assign a value to the array at runtime, it still is considered undefined.

CodePudding user response:

On

return (
        {storeInputs.map(store,index) => 
        {
            //input data here
            
            {storeInputs.items.map(item,i) => 
                {
                    //This is where it throws the undefined error
                    //do something
                }
            }
        }
    )

You map two time on storeInputs, you need to do someting like :

return (
        {storeInputs.map((input,index) => 
    {
        //input data here
        
        {input.items.map((item,i) => 
            {
                //This is where it throws the undefined error
                //do something
            }
        }
    }
)

Be careful about the () around the params, you do :

x.map(a, index) => {})

In fact is :

x.map((a, index) => {})

The first ( is for the map methods, second is for the params of the function inside your map.

CodePudding user response:

The storeInputs state hasn't any items property to map in the inner mapping. That property belongs to the store object mapped from the outer loop.

function StoreForm() {
  const [storeInputs, setStoreInputs] = useState([
    { storeName: "", items: [{ itemName: "" }] },
  ]);
  
  ...
    
  return storeInputs.map((storeInput, index) => {
    // input data here
  
    return (
      ...          
      {storeInput.items.map((item, i) => { ... })}
      ...
    );
  });
}
  • Related