Created
November 17, 2019 09:41
-
-
Save webmasterdevlin/0d48de87d9bfd6c21f0d812c418322a9 to your computer and use it in GitHub Desktop.
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 React, { createContext } from "react"; | |
import { useLocalStore } from "mobx-react-lite"; | |
import { | |
deleteHero, | |
getHeroById, | |
getHeroes, | |
postHero, | |
putHero | |
} from "./hero-service"; | |
export const HeroProvider = ({ children }) => { | |
const store = useLocalStore(() => ({ | |
/*observables here*/ | |
/*actions*/ | |
async getHeroes() { | |
store.isLoading = true; | |
try { | |
store.heroes = (await getHeroes()).data; | |
} catch (e) { | |
store.setError(e); | |
} | |
store.isLoading = false; | |
}, | |
async getHeroById(id) { | |
store.isLoading = true; | |
try { | |
const { data } = await getHeroById(id); | |
store.hero = data; | |
} catch (e) { | |
store.setError(e); | |
} | |
store.isLoading = false; | |
}, | |
async postHero(newHero) { | |
store.isLoading = true; | |
try { | |
store.heroes.unshift((await postHero(newHero)).data); | |
} catch (e) { | |
store.setError(e); | |
} | |
store.isLoading = false; | |
}, | |
// pessimistic UI update | |
async deleteHero(id) { | |
store.isLoading = true; | |
try { | |
await deleteHero(id); | |
store.heroes = store.heroes.filter(h => h.id !== id); | |
} catch (e) { | |
store.setError(e); | |
} | |
store.isLoading = false; | |
}, | |
async putHero(updatedHero) { | |
store.isLoading = true; | |
try { | |
await putHero(updatedHero); | |
const index = store.heroes.findIndex(h => h.id === updatedHero.id); | |
store.heroes[index] = updatedHero; | |
} catch (e) { | |
store.setError(e); | |
} | |
store.isLoading = false; | |
}, | |
setHero(hero) { | |
store.hero = hero; | |
}, | |
setError({ message }) { | |
store.error = message; | |
alert(message); | |
} | |
})); | |
return <heroContext.Provider value={store}>{children}</heroContext.Provider>; | |
}; | |
export const heroContext = createContext(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment