2

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:

enter image description here

Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
  • I don't fully understand the question. State is not persistent - it is cleared when the app is closed or reloaded - so at the instant the app loads, state only has the provided initial value, which in this case is `[]`. Is that your problem, or is the `fetchData` function not succeeding? Is there any error message you can provide? – ChiefMcFrank Feb 05 '22 at 17:46
  • Yes, the fetchData function is not succeeding. I'm not getting any error, just the console.log(images) is giving me an empty array even though console.log(res) is showing all the data I want but it is not getting stored in images state. – piyush shende Feb 05 '22 at 17:51
  • If `console.log(res)` shows data, `fetchData` is succeeding. It sounds like `setImages` is not working. Can you update your question with those details, as well as the fetch result? – ChiefMcFrank Feb 05 '22 at 18:11
  • I updated the question. Please have a look and please correct me. – piyush shende Feb 06 '22 at 05:19
  • set function fetchData out of useEffect – A.R.SEIF Feb 06 '22 at 05:36

1 Answers1

3

Setting state in React is asynchronous so you will not be able to see your images immediately on the next line after setting the state.

useEffect(() => {
   function fetchData(){
       instance.get('/Index/getphoto')
       .then(res=>{
           console.log(res);
           setImages(res.data);
       })
    }
    fetchData();
}, [])
// Moved this log outside useEffect
console.log(images);

And about the warning you are getting is related to unique keys is because you are using map over images so you need to assign unique keys to each element inside map.
In your case, you are using item.id so just make sure the id is unique for all images otherwise it will not behave as expected.

 <div key={item.id}>

References -

  1. ReactJS : What is the best way to give keys in array element
  2. Why calling react setState method doesn't mutate the state immediately?
  3. Correct path for img on React.js
  4. React won't load local images
Sagar Darekar
  • 982
  • 9
  • 14
  • Yes, It worked. Thank you so much. And can you please tell me if this line is correct.anything – piyush shende Feb 06 '22 at 05:46
  • Yes, It worked. Thank you so much. And can you please tell me, if the below line is correct? anything. I stored the name of the image with jpg or jpeg extension in MongoDB and tried to access it from there. But the image is not getting loaded on the client side. – piyush shende Feb 06 '22 at 05:53
  • storing images names in database is fine, but where are your actual images are stored? – Sagar Darekar Feb 06 '22 at 05:55
  • I have updated my answer with a few references, take a look it will help you understand and solve your problem. – Sagar Darekar Feb 06 '22 at 05:59