Home > Enterprise >  Can't fetch data with Axios and React, getting an Promise and Undefined
Can't fetch data with Axios and React, getting an Promise and Undefined

Time:12-07

I'm trying to fetch some data with Axios and React, But I'm having a problem resolving the promise and setting it on the state, that's weird.

Here is the Base:

export const fetchUserById = (username) => client.get(`/${username}`);

Here is the Call:

export const getUserById = async (username) => {
   try {
      const response = await api.fetchUserById(username);
      const data = await response.data;
      return data;
   } catch (error) {
      return error;
   }
};

Here is in React:

const [user, setUser] = useState();
    
    useEffect(() => {
        const data = getUserById(params.username); // this gets the username and its working
        setUser(data)
    }, [])

    useEffect(() => {
        console.log("this is user: ", user)
    }, [user])

If I console log user, I get undefined, If I console log data i get a promise.

CodePudding user response:

getUserById is declared async so it implicitly returns a Promise that callers should either await or use a Promise chain on.

useEffect(() => {
  const data = getUserById(params.username);
  setUser(data); // <-- logs only the returned Promise object!
}, [])

async/await

useEffect(() => {
  const getUser = async () => {
    try {
      const data = await getUserById(params.username);
      setUser(data);
    } catch(error) {
      // handle error, log, etc...
    }
  };

  getUser();
}, []);

Promise chain

useEffect(() => {
  getUserById(params.username)
    .then(data => {
      setUser(data);
    })
    .catch(error => {
      // handle error, log, etc...
    });
  };
}, []);

CodePudding user response:

Or you could as well do:

useEffect(() => {
  // fetch data
  (async () => {
    try {
      const data = await getUserById(params.username);
      // set state
      setUser(data) 
    } catch(error) {
      // handle error, log, etc...
      // set init state
      setUser(null) 
    }
  })();
 
}, []);
  • Related