Last active
November 16, 2019 23:49
-
-
Save webmasterdevlin/5b31f5a8744c89320639ece31b8b9429 to your computer and use it in GitHub Desktop.
Add thunks to perform side effects
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 { 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*/ | |
getHeroes: thunk(async actions => { | |
actions.setIsLoading(); | |
try { | |
const { data } = await getHeroes(); | |
actions.setHeroes(data); | |
} catch (e) { | |
actions.setError(e); | |
} | |
actions.setIsLoading(); | |
}), | |
getHeroById: thunk(async (actions, id) => { | |
actions.setIsLoading(); | |
try { | |
const { data } = await getHeroById(id); | |
actions.setHero(data); | |
} catch (e) { | |
actions.setError(e); | |
} | |
actions.setIsLoading(); | |
}), | |
postHero: thunk(async (actions, newHero) => { | |
actions.setIsLoading(); | |
try { | |
const { data } = await postHero(newHero); | |
actions.addHero(data); | |
} catch (e) { | |
actions.setError(e); | |
} | |
actions.setIsLoading(); | |
}), | |
// Pessimistic UI update | |
deleteHero: thunk(async (actions, id) => { | |
actions.setIsLoading(); | |
try { | |
await deleteHero(id); | |
actions.removeHero(id); | |
} catch (e) { | |
actions.setError(e); | |
} | |
actions.setIsLoading(); | |
}), | |
putHero: thunk(async (actions, updatedHero) => { | |
actions.setIsLoading(); | |
try { | |
await putHero(updatedHero); | |
actions.updateHeroes(updatedHero); | |
} catch (e) { | |
actions.setError(e); | |
} | |
actions.setIsLoading(); | |
}) | |
}); | |
export default HeroStore; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment