1

The code is:

var data;

axios.get('http://localhost:3000/api/goodNews').then(result => {
    data = result;  
    console.log(data); //This work
    return data;
});

console.log(data)//this don't work

The goal is to get the answer from axios to use in the component where this code is. However, I can't get this information out of the Then () function. Sometimes it returns undefined, and if you do:


    var data;

    data = axios.get('http://localhost:3000/api/goodNews').then(result => {
        return result
    });

    console.log(data)//this don't work

It's return "Promise { }"

I already tryed:

1

    async function  getData(){
        var response = await axios.get('http://localhost:3000/api/goodNews').then(result => {
            return result
        });

        return response
    }

    var data = getData();

    console.log(data);

2

    const [data, setData] = useState(null)
   
    axios.get('http://localhost:3000/api/goodNews').then(result => {
        setData(result);
        return data;
    }).catch(function (error) {
        console.log(error);
    });
    
    console.log(data);

3


    const [data, setData] = useState(null)

    const getData = async ()=>{

        
        var response = await axios.get('http://localhost:3000/api/goodNews').then(result => {
            return result;
        });

        setData(response)
        return response;
    }

    getData();

    console.log(data);
    

OBS: I'm inside of a React Component and wanna to use the data inside of the returning TML

How do I do to return the data from the then() function?

Renato
  • 121
  • 1
  • 8
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – maazadeeb Jan 26 '21 at 17:23
  • Does this answer your question? [Fetching data with axios in react](https://stackoverflow.com/questions/55228930/fetching-data-with-axios-in-react) – Rashomon Jan 26 '21 at 17:24

4 Answers4

0

you can use useState to assign the response from then function

first define it

const [apiData,setData] = useState(null) 

then in the request

update:

axios.get('http://localhost:3000/api/goodNews').then( res => setData(res))

after that

  console.log(apiData)//the useState value

whole code

const [data, setData] = useState(null)
useEffect(()=>{
        axios.get('http://localhost:3000/api/goodNews').then(res=> 
    setData(res.data));
 },[])

Now whenever you send a request and get response, then function add the response to data

Yaya
  • 4,402
  • 4
  • 19
  • 43
  • but this broke the code again, with the error: TypeError: Assignment to constant variable. at C:\Users\refba\github\nextJsTest\.next\server\pages\timeLine.js:4071:10 at runMicrotasks () at processTicksAndRejections (internal/process/task_queues.js:93:5. – Renato Jan 26 '21 at 17:48
  • and if I fix this, still returning "null" the old value – Renato Jan 26 '21 at 17:48
  • Yes I tryed it. But now it returs "null" – Renato Jan 26 '21 at 18:09
  • what if you remove return like i did in new updated answer? – Yaya Jan 26 '21 at 18:15
  • I remove it, still returning null.... I think need to use setState – Renato Jan 26 '21 at 18:20
  • if you're using `then()` no need to use async await you should call the request in useeffect I'm updating the answer – Yaya Jan 26 '21 at 18:29
  • important : make sure you `setData(res.data)` and not `setData(res)` do this and tell me the result – Yaya Jan 26 '21 at 18:36
  • do you use the `data` somewhere inside your react component(except for console.log)? if you do try to remove it and rerun the app – Yaya Jan 26 '21 at 18:51
  • I think it's work. Will try somt other things. Thanks <3 – Renato Jan 26 '21 at 18:52
  • i'm glad to help – Yaya Jan 26 '21 at 18:53
0

There are two ways to do that.

  1. async/await
var data;

data = await axios.get('http://localhost:3000/api/goodNews').then(result => {
    return result;
});

  1. by using promise, you can not get the result from the axios call.
Everest Climber
  • 1,203
  • 1
  • 9
  • 15
0

Axios performs an asynchronous request and therefore it's return value is not the actual data but it returns a promise object. If you want to access the data obtained by axios outside the get request, you can make use of the promise object returned by axios.

Here is an example snippet:

function getSrc() {   
    return axios.get('assist/img/src');
}

getSrc.then(function (response) {
    return response.data; // now the data is accessable from here.
}).catch(function (response) {
    console.log(response);
});

Axios is designed this way so that it can help with asynchronous tasks. Hope this answers your question.

0

actually when you do it this way:

var data;

data = axios.get('http://localhost:3000/api/goodNews').then(result => {
    return result
});

console.log(data)

the data is not readily available at that time, and it will log Promise object. If youre doing it inside a function, you can use async-await reserved keywords to wait for the value (remember, you can only use await inside async function)


function async getData(){
var data;

data = await axios.get('http://localhost:3000/api/goodNews').then(result => {
    return result
});

console.log(data)
}

but, technically youre still using Promise but in different form.

Hadi KAR
  • 384
  • 3
  • 11