0

I'm using the request npm package, which is just a promise wrapped in an HTTP call. I've had issues with promises in the past. How do I get a promise to return a value so I can use it in react or get a promise to set a react state variable within that promise? I need a specific number from an API call to set a react state variable.

For code like so...

request(options, function (error, response, body) {
        if (error) throw new Error(error);
        console.log(Number(JSON.stringify(body).split(",")[2].split(":")[1]);
    });

and

GetHeadBlock = async () => {
        request(options, function (error, response, body) {
            body => Number(JSON.stringify(body).split(",")[2].split(":")[1]);
            this.setState({numberofHeadBlock: body})
        });
    }
  • Your second snippet should setState. But why are you using `.split(",")[2].split(":")[1]` on a JSON string, why not get the value straight from the javascript object? Eg if the object was `{key1:3,key2:4,key3:1}` you would just do `{numberfoHeadBlock:body.key3}` – Patrick Evans Nov 21 '19 at 21:48
  • It returns a value of undefined in my current context. – Fifth Dimension Dragon Nov 22 '19 at 00:45

1 Answers1

0

I used the Request Promise library to have a promise returned. Then used the "that" keyword to introduce proper scope and used neatly placed return statements for a solid closure.

Massfunc = async () => {
    var that = this;
    var promise = rp(options).then(function (body) {
        let returnedValue = Number(JSON.stringify(body).split(",")[2].split(":")[1]);
        that.setState({num: returnedValue});
        return returnedValue;
    }).catch(function (err) {
        console.log(err);
    });
    return promise;
  }