Whenever I call for the useState variable inside the functional component of react, before return section, if I set an array/object with values in useState, it always sends me an empty array/object. As a result, whenever I map it, it sends undefined. I want to wait for the value to come first without getting an empty value. how to do it?
import React from 'react';
import { Link } from 'react-router-dom';
import './HomeBike.css';
import { useEffect, useState } from 'react';
import MyOrder from '../../MyOrder/MyOrder';
const Home = (props) => {
const [shel, setShel] = useState([]);
setShel(['friend', 'sath']);
console.log(shel);
const { name, s_details, image, _id } = props.service;
return (
<div>
<div className="col h-100">
<div className="card h-100">
<img src={image} className="card-img-top service-img" alt="..." />
<div className="card-body">
<h5 className="card-title">{name}</h5>
<p className="card-text">{s_details}</p>
</div>
<div className="card-footer">
<div className="d-grid gap-2">
<Link to={`/details/${_id}`}>
<button className="btn btn-primary" type="button">Pucrchase Details</button>
</Link>
</div>
</div>
</div>
</div>
</div>
);
};
export default Home;
CodePudding user response:
React this.setState
, and React.useState
create queues for React core to update the state object of a React component.
So the process to update React state is asynchronous for performance reasons. That’s why changes don’t feel immediate.
const Home = (props) => {
const [shel, setShel] = useState(['friend', 'sath']);
console.log(shel);
const { name, s_details, image, _id } = props.service;
return (
<div>
<Your code...>
</div>
);
};
export default Home;