-
-
Save spac3unit/b8ea62ab7cd88462f13c8e0e90311018 to your computer and use it in GitHub Desktop.
Async Fetching with MobX Actions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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