0

I call a function inside react render with this code

    {this.getChar({char})}

I have a function to return value from axios

    getChar(url){
        var res = ''
        axios.get(url).then( datas => {
                res = datas.name
                console.log(datas.name)  
        });
        return res
    }

If i run the getchar function, in my console will display string as i want, but how to send that string to 'res' variable so i can return a string from the getChar function ?

In example, if i run

    var url = 'https://some/url/'

and i call getchar function

    getChar(url)

it will display

    result

Thanks for help

Lancelot
  • 3
  • 1
  • 1
    This question will almost certainly get closed as a duplicate, as variants of this question get asked at least once a day. Where you have res = datas.name, use something like `this.setState({res: datas.name})`. And then render `this.state.res`. Call this.getChar() inside the render function before `return`, or somewhere else appropriate. – see sharper Jan 10 '20 at 05:06
  • 1
    First off, you have timing problems in your getChar function. It will return res long before axios.get(...) completes. Secondly this gets answered a lot: https://stackoverflow.com/a/49890315/3236706 – BlueWater86 Jan 10 '20 at 05:09
  • 1
    Read on `asynchronous` programming and working of `Promises` in JS – arjun Jan 10 '20 at 05:10

0 Answers0