'Return value from function React from an Axios' response

I have this function in React that should export the result got from an Axios' API call:

import axios from 'axios'

export function youtube(channelId) {

    var config = {
    method: 'get',
    url: `https://www.googleapis.com/youtube/v3/channels?part=statistics&id=${channelId}&key=AIzaxXXXXXXXXXXXXXXXXXXXXXX`,
    headers: { }
    };

    axios(config)
    .then(function (response) {
        console.log(response.data.items[0].statistics.subscriberCount)
        return response.data.items[0].statistics.subscriberCount
    })
    .catch(function (error) {
        return 0
    });
    

} 

Problem: it returns undefined. But the console.log displays the correct data.



Solution 1:[1]

In a Synchronous way that is not possible but yes in an asynchronous way, it's possible, As per our comment discussion, you are accessing the promise and for asynchronous tasks, you need to resolve it to return any value or use async/await for better reading purposes.

In your code, the problem is you are returning in then/catch, another then/catch will be waiting for your input, it will not succeed until you will not settled the promise.

Codesandbox: https://codesandbox.io/s/divine-cherry-dqu40?file=/src/App.js

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nisharg Shah