Fetch is an asynchronous function. Execution continues to the next line until the request completes. You need to queue the code to run after the request is complete. The best way to do this is to force your postAuthor method to return the promise, and then use the promise method. Then in the caller.
class ManageAuthorPage extends Component { // ... postAuthor() { return fetch(source, { method: 'post', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ id: this.generateId(this.state.author), firstName: this.state.author.firstName, lastName: this.state.author.lastName }) }); }; saveAuthor(event) { event.preventDefault(); this.postAuthor().then(() => { this.props.history.pushState(null, '/authors'); }); }; // ... }
If you use a transpiler that supports async ES7 functions, you can even do this in your saveAuthor method, which is equivalent and easier to read:
async saveAuthor(event) { event.preventDefault(); await this.postAuthor(); this.props.history.pushState(null, '/authors'); };
source share