Search code examples
reactjsaxiosresponse

Why inside the then() the data exist, and out side doesn't - Axios returning undefined


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?


Solution

  • 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