Skip to content

Instantly share code, notes, and snippets.

@mkhuda
Forked from alexvcasillas/github-store.js
Created July 31, 2018 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkhuda/eed8001d6f50b6fb94891b96a753f177 to your computer and use it in GitHub Desktop.
Save mkhuda/eed8001d6f50b6fb94891b96a753f177 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;
});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment