Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the right way to store a object in React

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:""}]);

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading