Skip to content

Instantly share code, notes, and snippets.

@webmasterdevlin
Created November 16, 2019 23:48
Show Gist options
  • Save webmasterdevlin/9136a1640748da04ab110d9a823545a6 to your computer and use it in GitHub Desktop.
Save webmasterdevlin/9136a1640748da04ab110d9a823545a6 to your computer and use it in GitHub Desktop.
Adding actions to your model
import { action, computed, createContextStore, thunk } from 'easy-peasy'
import { deleteHero, getHeroById, getHeroes, postHero, putHero } from './hero-service'
const HeroStore = createContextStore({
/*states here*/
/*actions thunk side effects here*/
/*actions*/
setHeroes: action((state, heroes) => {
state.heroes = heroes;
}),
setHero: action((state, hero) => {
state.hero = hero;
}),
setError: action((state, error) => {
state.error = error.message;
alert(error.message);
}),
setIsLoading: action(state => {
state.isLoading = !state.isLoading;
}),
addHero: action((state, newHero) => {
state.heroes.push(newHero);
}),
removeHero: action((state, id) => {
state.heroes = state.heroes.filter(h => h.id !== id);
}),
updateHeroes: action((state, updatedHero) => {
const index = state.heroes.findIndex(h => h.id === updatedHero.id);
state.heroes[index] = updatedHero;
})
});
export default HeroStore;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment