1

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. 
Zoe
  • 27,060
  • 21
  • 118
  • 148
User_KA
  • 37
  • 8
  • If i move the logic of foo() to the constructor this works but it get the value just once the page is refreshed which is not the workflow that i am trying to achieve – User_KA Jun 08 '18 at 14:08
  • Have you tried using this approach? https://stackoverflow.com/questions/38742334/what-is-right-way-to-do-api-call-in-react-js – Will Jun 08 '18 at 14:42

1 Answers1

0

As I can see, you want to call update() just after foo() finishes, right? As it is on your code, it will call both before foo() response arrives from the server.

You should use the Promise that you are returning on your ajax calls:

foo() {
    return Manage.foo() // return the promise that Manage.foo returns
        .then(data => {
            this.setState({ test: "result_from_foo" });
        });
}

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

    // you have a type error here, it must be update, not Update
    return Manage.update(np, sd).then(()=> { // return the promise that Manage.update returns
      //rest of the code, running after Manage.update returns
    });
}
handlefoo() {
    this.foo().then(() => { // here, call update just after foo completes
        this.update();
    });
}
Murilo Cruz
  • 2,387
  • 1
  • 17
  • 19