Cannot save data returned from fetch on a functional component

Viewed 25

I'm trying to get a certain return value (of type string) from fetch() but I'm failing, allthough the data is there when I try to display it on console. The thing is that I need to do in a "function Component". That means it works in a "class Component" with setState. here is the code : too simple

import {useState} from 'react';
 
function ProfilePhoto(props) {
    const [data,setData]=useState(()=>fetch(url)
    .then((response)=>response.json())
    .then((data)=>{
        console.log(data);
        return data.userPhoto;}));

    return (
        <div>
            {"data: "+data}
             <input  id="picture" type="file" name="file" />
                <img src={"./images/"+ data}></img>
        </div>
    );
}

export default ProfilePhoto;

Data in console:

{id: 1, username: 'Paul', userPhoto: 'photo1.jpg', posts: Array(4), login: null, …}

1 Answers

If you want to fetch data and store it to state, I suggest using useEffect.

import {useState, useEffect} from 'react';
 
function ProfilePhoto(props) {
    const [data,setData]=useState();

    useEffect(() => {
      fetch(url)
      .then((response)=>response.json())
      .then((newData)=>{
          console.log(newData);
          setData(newData)
    }, [])

    return (
        <div>
            {"data: "+data}
             <input  id="picture" type="file" name="file" />
                <img src={"./images/"+ data}></img>
        </div>
    );
}

export default ProfilePhoto;

Passing an empty array [] as the second parameter of useEffect tells it to run the function in the first parameter once, after the component is initially rendered. Then you can update state using setData. The problem is you are trying to set the initial value of useState to an unresolved promise. It will not update the state after the promise resolves unless you use setData.

Related