Home > Net >  What is the right way to store a object in React
What is the right way to store a object in React

Time:11-02

I want to store my Object of my Checkout-Cart in a React Variable. I tried it with the useState Component but that did not work.

This is my object which I get from my NodeJs Backend : `

[
  {
    product_uuid: '3bef830f-a06d-4562-8793-bb94f725226a',
    product_quantity: 1,
    product_name: 'Example Product',
    product_price: 30,
    product_img: ''
  }
]

And this is my code on how to store it:

var cart=[{}];
  useEffect(() => {
    Axios.post("http://localhost:3001/products/getCart", {
    }).then((response)  => {
        if(response.data.error){
        }else{
          cart = response.data.finished_cart;
          console.log(response.data.finished_cart)
    }
    console.log(cart)
  });
  }, []);

When i log the cart in this part of the code everything works fine and I get my Object stored but when i want to access it in the jsx part it is undefined:

return (
    <div>
    {console.log(cart)}
    </div>
)

I also tried to store the cart with this method but this does not work:

//Method 1
const[cart,setCart]=useState([{}]);
//Method 2
const[cart,setCart]=useState([{product_uuid:0,product_quantity:0,product_name:"",product_price:0,product_img:""}]);

CodePudding user response:

The useState direction is the way to go. After you get your cart result back you should use the setCart function to update your state, which will re-render your component with the new cart value

  setCart(response.data.finished_cart);
  • Related