Skip to content

Instantly share code, notes, and snippets.

@alexvcasillas
Created May 4, 2017 08:35
Show Gist options
  • Save alexvcasillas/104185e99bb61c5d4d018ccedb66c4b0 to your computer and use it in GitHub Desktop.
Save alexvcasillas/104185e99bb61c5d4d018ccedb66c4b0 to your computer and use it in GitHub Desktop.
Async Fetching with MobX Actions
import fetch from 'node-fetch';
import { observable, action, runInAction } from 'mobx';
export default class GithubStore {
@observable searchName;
@observable user;
@observable repos;
@observable fetchingData;
constructor() {
this.searchName = '';
this.user = '';
this.repos = [];
this.fetchingData = false;
}
async fetchFromGithub(endpoint) {
const url = `https://api.github.com${endpoint}?client_id=my_client_id&client_secret=my_client_secret_id`;
const response = await fetch(url);
return await response.json();
}
@action('Change User to search for')
changeUserToSearchFor(username) {
this.searchName = username;
}
@action('Search for user on Github')
searchForUser = async () => {
if (!this.searchName) return;
this.fetchingData = true;
const [user, repos] = await Promise.all([
this.fetchFromGithub(`/users/${this.searchName}`),
this.fetchFromGithub(`/users/${this.searchName}/repos`)
]);
runInAction("Update State after fetching Github's Data", () => {
this.user = user;
this.repos = repos;
this.fetchingData = false;
});
};
}
@Akhtar69
Copy link

zdcZXczxczxczxcczxcc

@oulhtak
Copy link

oulhtak commented Jan 3, 2023

using runInAction in this case would not provide any additional benefits – the updates to the user and repos variables would already be wrapped in a transaction by the @action decorator.

@vitaliyslion
Copy link

using runInAction in this case would not provide any additional benefits – the updates to the user and repos variables would already be wrapped in a transaction by the @action decorator.

This is wrong actually. Whatever happens after "await" is not a part of the caller function anymore. So you have to either wrap it into "runInAction" or create a separate action.
async/await is a syntax sugar that removes "Promise.then" construction, but under the hood it is still simply a callback in ".then" and you have to wrap it for mobx.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment