Home:ALL Converter>Value doesn't change using setState() ,React nested API call

Value doesn't change using setState() ,React nested API call

Ask Time:2018-06-08T22:06:48         Author:User_KA

Json Formatter

The scenario is quite simple a first call will perform a "GET" request and setState() with the result, the second call will "POST" it.

Manaje.js

export default class Manage extends Component {
    static foo() {
        return adalApiFetch(fetch, 'api/Users/Generate', {
            method: "get",
            headers: { 'Content-Type': 'application/ json' }
        })
            .then(response => response.json())
            .catch(err => console.log(err));
    }

    static update(np, sd) {
        return adalApiFetch(fetch, 'api/Users/Update', {
            method: "post",
            body: JSON.stringify({ np: np, sd: sd }),
            headers: { 'Content-Type': 'application/ json' }
        });
    } }

Reset.js

export default class Reset extends Component{
    constructor(props) {
        super(props);
        this.state = { test: 'test' };
        this.update = this.update.bind(this);
        this.foo = this.foo.bind(this)
        this.handlefoo = this.handlefoo.bind(this);
    }

foo() {
    Manage.foo()
        .then(data => {
            this.setState({ test: "result_from_foo" });
        });
}

update() {
    var np = this.state.test;

    Manage.Update(np, sd){
      //rest of the code
    }
}
 handlefoo() {
        this.foo();
        this.update();
    }

//=>habldefoo triggered later in the render()
// <div><Button onClick={this.handlefoo} disabled={this.state.selectAll === 0} bsStyle="success">foo</Button></div>

The error:

Error: value of this.state.test is always 'test' as set initially. 

Author:User_KA,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/50762465/value-doesnt-change-using-setstate-react-nested-api-call
yy