Home > Software engineering >  Reactjs creating a array containing a bunch of objects using hooks
Reactjs creating a array containing a bunch of objects using hooks

Time:11-24

I'm trying to create a array which contains a bunch of objects like this and insert them upon different actions:

[
{price: 'price_1M73OzIRkO5W1JretwretkAHa', quantity: 1},
{price: 'price_1M73OzI4545W1JretwretkAHa', quantity: 3},
{price: 'price_1M73OzIRkO4545twr45kAHa', quantity:2}
]

However I cant seem to add in a third object it just overwrittes the second one.

const [allPlans, setAllPlans] = useState([]);

setAllPlans([{...allPlans, price:'price_1M73OzIRkO5W1JretwretkAHa', quantity: 1}]);

Thank you for the help!

update: Early in the code I do do this to update the quanity on the orginal entry. Could this be creating the issue?

setAllPlans({...allPlans,"quantity": userAmount});

CodePudding user response:

Try this method:

setAllPlans(allplans => [...allplans, {price:'price_1M73OzIRkO5W1JretwretkAHa', quantity: 1}]);

Here's an additional link demonstrating how this works: https://codesandbox.io/s/react-hooks-playground-forked-ooi7og?file=/src/index.tsx

CodePudding user response:

Maybe there is a cleaner way to do it, but you can try to do it with push method where prevPlans is going to be your initial array and you can add specific objects into that array.

setAllPlans((prevPlans) => [
      prevPlans.push({
        price: "i'm new here",
        quantity: 1
      })
    ]);

const {
  useState
} = React;

const App = () => {
  const [allPlans, setAllPlans] = useState([{
      price: "price_1M73OzIRkO5W1JretwretkAHa",
      quantity: 1
    },
    {
      price: "price_1M73OzI4545W1JretwretkAHa",
      quantity: 3
    },
    {
      price: "price_1M73OzIRkO4545twr45kAHa",
      quantity: 2
    }
  ]);

  const addtoArray = () => {
    //prevPlans is your actual array and you push new object inside it and set your state
    setAllPlans((prevPlans) => [
      prevPlans.push({
        price: "i'm new here",
        quantity: 1
      })
    ]);
    console.log(allPlans);
  };

  return ( <
    div >
    <
    button onClick = {
      () => addtoArray()
    } > Click me < /button> <
    /div>
  );

}


// Render it
ReactDOM.createRoot(
  document.getElementById("root")
).render( <
  App / >
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

  • Related