import React, { useEffect, useState } from "react";
import { getParticularProduct } from "../services/productService";
import { Link, useParams } from "react-router-dom";
function ParicularProduct() {
const [product, setProduct] = useState({});
const { id } = useParams();
useEffect(() => {
try {
getParticularProduct(id).then((response) => {
setProduct(response.data.product);
});
} catch (error) {
console.log(error.response.data);
}
});
console.log(product);
return (
<>
<div className="flex w-full border border-solid">
<div className="flex flex-row border border-solid w-full mt-20 p-5">
<img className='w-1/3' src={"http://" + product.images.host} />
{/* <div className="w-2/3">{product.name}</div> */}
</div>
</div>
</>
);
}
export default ParicularProduct;
In the useEffect hook setProduct can not change the data if my img tag is open. But if I comment out my img tag then "console.log(product)" run unlimited time and log the product data unlimited time. I also tried useEffecct hook with an blank dependency array. But it not rendered 1st time. if i change something in my code it re-rendered and showing the result and if i refresh the page it returns the default state"{}"
Please help. Thank You…
2
Answers
Your code is a very good example of some common pitfalls using hooks. Firstly,
useEffect
without dependency array will run every time any state or prop changes. That is the same as not usinguseEffect
hook at all. So, please always add dependency array to youruseEffect
.In this case, you want
useEffect
to run only once when the component is mounted. So, pass in an empty array.I believe this should solve the issue. However, please do this one change. If it does not work, update your question to include the new error message.
Happy coding!