0

So I'm mutating array in a correct way. But console.log(items) not print out the newly added element even though variable watch shows items has it, console.log(inventory.items) print out has the newly added one.

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

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

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

        setItems(vitems);   
        // OK if: setInventory({items: vitems});

        console.log(items);   // prints up to previous state without the newly added item.       
        // OK if: inventory.items HAS the newly added item. 
    }
    
  return (
    <div className="App">
        <AddItem callback={receiveAndAddAnItem} />
        <hr />
        <DisplayItems items={items}/>  // ???
        // OK if: items={inventory.items}
    </div>
  );
}
Jeb50
  • 5,215
  • 6
  • 32
  • 55

0 Answers0