'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":"[email protected]",
      "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 1:[1]

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: "[email protected]",
    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

Solution 2:[2]

I think this should answer your question for mocking up a static data. as per your example, the array has only one object.

import React, { useState } from "react";
const products = [
  {
    user: "[email protected]",
    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",
  },
];
const Demo = () => {
  const [quantity, setQuantity] = useState(products[0].qty);

  return <h1>{quantity}</h1>;
};

export default Demo;

otherwise, if you would like to set the state to a dynamic data, then you should use useEffect hook as side effect to set the state after the component is mounted.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Amr