0

I have a function called get which fetches data from a local rest api

const  get = () => {
    axios.get(URL).then((response) => {
        console.log(response)
        return response;
    }).catch((error) => {
        console.log('ERROR', error)
        return error
    })
}

Then within App.js i have used the function

  useEffect(() =>{
    const response = Data.get();
    console.log(response)
    setPersons(response.data)
  }, []);

The console.log(response) within the get function is returning the rest api data while the useEffect() is logging undefined Anybody have any idea why it is not returning the same?

2 Answers 2

1

Looks like you're missing a return statement in the get() function. It should look like this:

const get = () => {
    return axios.get(URL).then((response) => {
        console.log(response)
        return response;
    }).catch((error) => {
        console.log('ERROR', error)
        return error
    })
}

That will cause Data.get() to return the Promise from axios.

You'll then need to wait for the returned Promise to resolve before you can log it from App.js.

You can do that with a .then:

 useEffect(() =>{
    Data.get()
      .then(response => {
        console.log(response)
        setPersons(response.data)
      });
  }, []);

Or an async function:

  useEffect(async () =>{
    const response = await Data.get();
    console.log(response)
    setPersons(response.data)
  }, []);
Sign up to request clarification or add additional context in comments.

Comments

0

The axios request is asynchronous. After you call Data.get the code continues onto the next line without waiting for the response. You could fix this by allowing your get function to accept a callback. Something like this:

const  get = (success, error) => {
    axios.get(URL).then((response) => {
        console.log(response)
        success(response)
    }).catch((e) => {
        console.log('ERROR', e)
        error(e)
    })
}
useEffect(() =>{
    Data.get(({data}) => setPersons(data), (error) => console.log(error));
  }, []);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.