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

Time:05-02

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"
     
}
]

CodePudding user response:

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.

CodePudding user response:

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

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

  • Related