1

I'm having problem with settings state value with a value returned from a function. Somehow, the state only bind itself to the function itself. How can I fix this?

Here is my constructor:

    this.state = {
        text: getText
    }

Here is the function that retrieves the

getText= () => {
    $.get('/webapi/gettext, function (data) {
        return data;
    }.bind(this));
};

but this works if I have it in the constructor.

constructor{
        $.get('/webapi/gettext, function (data) {
                        this.setState({ text: data });
        }.bind(this));
}

1 Answers1

3

You'll need to use componentDidMount hook:

componentDidMount() {
  $.get('/webapi/gettext, (data) => {
    this.setState({ text: data });
  });
}

For further help, see my another post.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
  • Or should I just have it in the constructor? What would be the right way? I thought by having it in a function and call it from the constructor would be better? –  Mar 01 '19 at 08:22
  • $.get('/webapi/GetStartupThings, (data) => { this.setState({ text: data }); });¨ I actually got 2 jquery which retrieves data. –  Mar 01 '19 at 08:28
  • Is it possible to call function form the component Did mount instead? As I'm going to use this jquery function more places. –  Mar 01 '19 at 10:30
  • If you're going to use the same in more places, then create a new function and inside that place the logic `$.get()` code and use them in `componentDidMount(){callYourfunction()}` and where ever you want. – Bhojendra Rauniyar Mar 01 '19 at 11:35
  • I see now that there are cases where I'm sending a parameter event and cases not. is it possible to use the same function or do I have to use two functions with same code? –  Mar 01 '19 at 11:52