Skip to content

Instantly share code, notes, and snippets.

@alexvcasillas
Created May 4, 2017 08:35
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • 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.

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