Search code examples
reactjsobjectundefineduse-state

How to set useState initial value of object which is already in my fake data?


I was declared a state named:

const [quantity,setQuantity] = useState(products.qty)

I need products.qty will be my initial state value but it showed undefined.

Below I attached my fake data object:

products =[{
      "user":"tareque@gmail.com",
      "name": "Mathis England",
       "img":   "https://i.ibb.co/C8JtD0Z/bicycle-1.png",
       "description": "Lorem ipsum dolor sit amet consectetur",
       "price": 300,
       "qty": 20,
       "supplier": "Velocy"
     
}
]

Solution

  • This code is working, you can see the value in the console and in h1

    import { useEffect, useState } from "react";
    import { products } from "./products";
    
    export default function App() {
    const [quantity, setQuantity] = useState(products[0].qty);
    
      useEffect(() => {
        console.log("qty = ", quantity);
      }, []);
    
      return (
        <div className="App">
          <h1>{quantity}</h1>
          <h2>Start editing to see some magic happen!</h2>
        </div>
      );
    }
    

    your data source file products.js

    export const products = [
      {
        user: "tareque@gmail.com",
        name: "Mathis England",
        img: "https://i.ibb.co/C8JtD0Z/bicycle-1.png",
        description: "Lorem ipsum dolor sit amet consectetur",
        price: 300,
        qty: 20,
        supplier: "Velocy"
      }
    ];
    

    https://codesandbox.io/s/blue-violet-bfg2h8?file=/src/App.js