I'm trying to get the images from the Nodejs
server. Whenever I refresh the page or open it for the first time the data is not getting stored in the React state
variable and hence the state value is giving null
due to which I can't display the images on the client-side.
This is my React code:
const Images = ()=>{
const [images,setImages] = useState([]);
var res=[];
useEffect(()=>{
function fetchData(){
instance.get('/Index/getphoto')
.then(res=>{
console.log(res);
setImages(res.data);
console.log(images);
})
}
fetchData();
},[])
return(
<>
{
images.map((item)=>{
return(
<div key={item.id}>
<img src={`http://localhost:3000/${item.img}`} alt="anything" />
</div>
)
})
}
</>
);
}
In the above fetchData
function I'm getting all the data from an endpoint but when I try to store that data in images
state variable using setImages(res.data)
, it is not getting stored there and I'm getting the below result in my console: