Comments (10)
hi, createStore
exposes setGlobalState
, so you can use it to set something from anywhere.
setGlobalState('foo', localStorage.getItem('foo'));
Another way is to initialize initialState
with localStorage data.
Hope it helps.
from react-hooks-global-state.
Actually, there's an example: https://github.com/dai-shi/react-hooks-global-state/tree/master/examples/13_persistence
from react-hooks-global-state.
@dai-shi thanks for helping. I got the point, however there is no applyMiddleware
function in react hooks (without using redux). Any idea how to handle the state change persistence?
from react-hooks-global-state.
applyMiddleware
is a simple function that we could create.
The 13_persistence
example is rather to emulate redux pattern.
Let me show the first one as an example, because that's something independent from redux pattern.
const { dispatch, useGlobalState, getGlobalState, setGlobalState } = createStore(
reducer,
initialState
);
const saveToLocalStorage = () => {
localStorage.setItem('foo', JSON.stringify(getGlobalState('foo')));
localStorage.setItem('bar', JSON.stringify(getGlobalState('bar')));
};
const loadFromLocalStorage = () => {
setGlobalState('foo', JSON.parse(localStorage.getItem('foo')));
setGlobalState('bar', JSON.parse(localStorage.getItem('bar')));
};
Notice error handling is omitted.
from react-hooks-global-state.
Sure, I've got the point of loading and saving to local storage (also, bootstrapping from local storage). What is not clear to me is how to update the local storage every time a new action is dispatcher, that is... where to put saveToLocalStorage
without using applyMiddleware
from redux.
Is it just another reducer that doesn't alter the state and it just call the saveToLocalStorage
function?
from react-hooks-global-state.
Oh, sorry. I see your point now. Hm, good question. Without middleware, only way to get notified is the hook. So, I'd do like this:
const { dispatch, useGlobalState: useGlobalStateOrig } = createStore(...);
const useGlobalState = (key) => {
const [state, update] = useGlobalStateOrig(key);
useEffect(() => {
localStorage.setItem(key, JSON.stringify(state));
});
return [state, update];
};
If dispatch is the only way to modify the state, you could also wrap dispatch (which should be better than hacking reducer.)
const dispatch = (action) => {
dispatchOrig(action);
saveToLocalStorage();
};
from react-hooks-global-state.
I understand now, like the last approach. enhancer
could help? I think it's undocumented....
from react-hooks-global-state.
enhancer
could help. I mean applyMiddleware
is the function to take middleware and return an enhancer.
https://github.com/dai-shi/react-hooks-global-state#parameters-1 says enhancer
but it doesn't tell the usage.
BTW, we also have this: https://github.com/dai-shi/react-hooks-global-state/wiki/Persistence
from react-hooks-global-state.
So, I ended up using the following (the example you posted are relative to using a custom reducer and a custom function getFromLocalStorage
inside the createStore
call:
import { getFromLocalStorage, saveToLocalStorage } from './util';
import { createStore } from 'react-hooks-global-state';
import { reduceReducers } from './util';
const initialState = {
cart: {
items: [],
}
};
// This is the main reducer
const reducer = (state, action) => { /* ... */ };
const { dispatch, useGlobalState } = createStore(
reduceReducers(
reducer,
// This additional reducer doesn't alter the state, it just store it
state => {
saveToLocalStorage(LOCAL_STORAGE_KEY, state, LOCAL_STORAGE_TTL_SECONDS);
return state;
}
),
// Bootstrapping from local storage, returning the initialState if storage is empty
getFromLocalStorage(LOCAL_STORAGE_KEY, initialState)
);
export { useGlobalState };
I didn't used a custom useGlobalState
because I would need to typehint all original parameters. I still don't know which approach is better... custom reducer vs overriding the dispatch.
from react-hooks-global-state.
Looks good. I think it's totally valid with the current API and the implementation.
Please close the issue if you don't have further questions. Thanks.
from react-hooks-global-state.
Related Issues (20)
- getGlobalState should not be used in render HOT 5
- Error calling createStore (Typescript 3.6.4) HOT 2
- Question: how do developers use this library? HOT 1
- Please add CHANGELOG for 0.17.0 HOT 1
- getGlobalState loses sync with useGlobalState after 0.17 HOT 8
- How to use Redux Devtools Extension HOT 3
- comparison to react-tracked and initial values for a state HOT 9
- Error: You cannot use <GlobalStateProvider> more than once. HOT 5
- How to separate reducer and Action Type then call it to combineReducers (Ex: 07_middleware) HOT 3
- Offline saved data for React Native HOT 11
- Be able to access multiple state keys with a single hook HOT 3
- Mocking useGlobalState with jest? HOT 8
- global state not preserved with Fast Refresh HOT 2
- Argument of type '"cart"' is not assignable to parameter of type 'never' HOT 5
- Asynchronous initial state HOT 4
- Is it possible to change a value outside a component? HOT 2
- Persistence with createGlobalState HOT 6
- How to easily reset state? HOT 1
- How to update the state in Bulk ? HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from react-hooks-global-state.