0

To display the full array content when a new item is added.

DisplayItems.js:

export default function DisplayItems(props)
{
    return (
        <div>
            {
                props.items.map
                ((i) => 
                    {
                        return (
                            <div>
                                ID: {i.id}, Name: {i.name}
                            </div>
                        )
                    }
                )                
            }
        </div>
    )
}

App.js:, lines with //??? not working and no error, but OK if replaced by // OK if : ..., difference is to move array into an attribute of an object: inventory.items.

import DisplayItems from './DisplayItems';
export default function App()
{
    const [items, setItems] = useState([]);   // ??? array
    // OK if: const [inventory, setInventory] = useState({ items: []});

    const receiveAndAddAnItem = (newItem) =>
    {
        let vitems = items;   // ??? 
        // OK if: let vitems = inventory.items; 

        let vid = vitems.length;
        let i = {id: vid, name: newItem.name};
        vitems.push(i);

        setItems(vitems);   // ??? not trigger DisplayItems for re-render
        // OK if: setInventory({items: vitems});
    }
    
  return (
    <div className="App">
        <AddItem callback={receiveAndAddAnItem} />
        <hr />
        <DisplayItems items={items}/>  // ???
        // OK if: items=(inventory.items)
    </div>
  );
}

Update Thanks to @NicholasTower, OK if copy then change: let vitems = [...items]

Jeb50
  • 5,215
  • 6
  • 32
  • 55
  • 1
    When you set state, react does a `===` between the old state and the new state. If they're the same, the component does not render. And since you're mutating the old state, the `===` passes. Make sure to copy your array and then change the copy. – Nicholas Tower May 15 '22 at 01:30

0 Answers0