I am trying to get a single product detail whenever I click on the button, but I get the wrong product detail on the first click, then get the correct product detail on the second click
const updateProducts = async (e) => {
const singleProduct = await axios.get(
`https://middlemen-backend.herokuapp.com/api/product/${id}`
);
console.log(singleProduct);
setproductDetails(singleProduct);
setid(e.target.value);
setopenModal(true);
};
The state for the id and the single product detail
const [productDetails, setproductDetails] = useState({});
const [id, setid] = useState(1);
below is the onclick button to get the single data
<div key={prod && prod.id}>
<button
onClick={updateProducts}
value={prod && prod.id}
>
Edit
</button>
</div>
CodePudding user response:
You're setting the id state after the axios request. You should also just use the e.target.value
as the URL param:
const updateProducts = async (e) => {
const idValue = e.target.value;
setid(idValue);
const singleProduct = await axios.get(
`https://middlemen-backend.herokuapp.com/api/product/${idValue}`
);
console.log(singleProduct);
setproductDetails(singleProduct);
setopenModal(true);
};