I am developing an ecommerce application and on productdetail page my main image is showing previous state ..only updates on refreshing page
const [mainImage,setMainImage] = useState(images[0])
return (
<div className="productdisplay-img-left">
{(images.length > 1) && (
images.map((image,index)=>(
<img key={index} onClick={()=>setMainImage(image)} src={`http://localhost:3000/public/products/${image}`}/>
))
)}
</div>
<div className="productdisplay-main-img">
<img src={`http://localhost:3000/public/products/${mainImage}`}/>
</div>
)
2
Answers
The code you’ve provided looks mostly correct, but it’s likely a problem with the state not updating properly or the event handling of the click event. Create a function that call on onClick event in the images.map()
Try this one to resolve the issue :