Skip to content

Instantly share code, notes, and snippets.

@TRomesh
Last active May 17, 2021 16:53
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 TRomesh/2c4fe6edcc7ee1e109aa6e7356e2f77b to your computer and use it in GitHub Desktop.
Save TRomesh/2c4fe6edcc7ee1e109aa6e7356e2f77b to your computer and use it in GitHub Desktop.
Store for Pokémon application with Hookstate
import { Persistence } from '@hookstate/persistence';
import { createState, useState, none } from '@hookstate/core'
const store = createState({
pokemon: { name: '', power: '', description: '' },
pokemons: [{ id: 1, name: 'pikachu', power: 'fire', description: 'fluffy' }],
isEditing: false,
})
const useGlobalState = () => {
const state = useState(store);
state.attach(Persistence('pk'))
return ({
get: () => state.value,
addPokemon: (pokemon) => {
state.pokemons.merge([pokemon])
},
deletePokemon: (id) => {
state.pokemons.keys.forEach(index => {
if (state.pokemons[index].id.get() === id) {
state.pokemons[index].set(none)
}
})
},
updatePokemon: (data) => {
state.pokemons.keys.forEach(index => {
if (state.pokemons[index].id.get() === data.id) {
state.pokemons[index].merge(data)
}
})
state.merge({ isEditing: false })
state.merge({ pokemon: { name: '', power: '', description: '' } })
},
selectPokemon: (pokemon) => {
state.merge({ isEditing: true })
state.merge({ pokemon: pokemon })
},
clearPokemon: () => {
state.merge({ isEditing: false })
state.merge({ pokemon: { name: '', power: '', description: '' } })
}
})
}
export default useGlobalState;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment