Tutorial on making Mobx Asynchronous Calls
In the last tutorial, we created our first Mobx ToDo app whose source code you can get from here. We will continue directly from that tutorial to make an asynchronous call to https://jsonplaceholder.typicode.com/todos?userId=1&completed=false
This is an jsonplaceholder API endpoint that will retrieve some ToDo items …
For the purpose of this tutorial, we are going to use axios to perform the fetch. So we install it with …
npm install axios
We will first do it the naive way and see why it doesn’t work and later how to fix. We create an action in the ToDo store to perform an axios fetch which returns a promise…
We will call this “getToDos” action in the ToDo componentDidMount …
When we run the app and inspect what was console out in the browser developer tool …
we see the structure of the ToDo objects that are retrieved in “response.data”. We just need the “title” from each object and append it in our observable array of toDos, so we use “map” to get an array of titles and then …
When you run the app, you will find that the “this” in the inner callback function is undefined.
So to fix this is to pass a callback function that is another action like this …
This works. Because now the success callback function “getToDosSuccess” is wrapped in an @action. And make sure to use the arrow function syntax (otherwise you would need @action.bound).
The nine ToDo items was fetched and loaded…
Here are the source files so far.