dai-shi / react-hooks-global-state

[NOT MAINTAINED] Simple global state for React with Hooks API without Context API
https://www.npmjs.com/package/react-hooks-global-state
MIT License
1.1k stars 62 forks source link

Ideas on persistence #4

Closed cupcakearmy closed 5 years ago

cupcakearmy commented 5 years ago

First off: awesome library! No deps, simple, clean, love it! ❤️

Are there any ideas for persistence? Right now I'm doing this and it works pretty good 💪

import { createStore } from 'react-hooks-global-state'

import { DispatchedAction } from './actions'
import reducer from './reducer'

export type State = {
    counter: number
}

const persistenceKey = 'my_cool_app_persistence'

const firstState: State = { counter: 0 }

const initialStringFromStorage = localStorage.getItem(persistenceKey)
const initialState: State = initialStringFromStorage === null
    ? firstState
    : JSON.parse(initialStringFromStorage)

const persistentReducer = (state: State, action: DispatchedAction) => {
    const mutated: State = reducer(state, action)
    localStorage.setItem(persistenceKey, JSON.stringify(mutated))
    return mutated
}

export const { GlobalStateProvider, dispatch, useGlobalState } = createStore(persistentReducer, initialState)

Maybe one could do a small github wiki entry and link it in the README. Any thoughts/ideas?

dai-shi commented 5 years ago

Hey, thanks!

I haven't thought much about persistence. It may take some time for me to think about how persistence support should be for createGlobalState. As for createStore, technically you can use Redux-style middleware, and it's probably better to do so instead of having side effects in a reducer. I'll make an example later, but meanwhile you can try that too.

Maybe one could do a small github wiki entry and link it in the README.

That sounds like a nice idea, because I want to keep the library itself small, but there would be many use cases and tips. Do you mean that I simply create a wiki placeholder in this repo?

cupcakearmy commented 5 years ago

That sounds like a nice idea, because I want to keep the library itself small, but there would be many use cases and tips.

Yes, keeping it small is a good idea.

Do you mean that I simply create a wiki placeholder in this repo?

Simply the repository wiki and add the link to the README.md 🙂

dai-shi commented 5 years ago

@CupCakeArmy I made an example. Hope it helps. Note that this is just one implementation, and there could be many. https://github.com/dai-shi/react-hooks-global-state/tree/master/examples/13_persistence

dai-shi commented 5 years ago

@CupCakeArmy The wiki is set up. Free free to edit it. I will add the link once we have several contents.

cupcakearmy commented 5 years ago

Maybe you can link it in the main README, so people can find it easily :)

https://github.com/dai-shi/react-hooks-global-state/wiki/Ideas