score:0
use localStorage:
localStorage.setItem('token', token);
And on load of app check if token is set, if it is, get info from localStorage
localStorage.getItem('token');
You can also save user info:
localStorage.setItem('user', JSON.stringify(userInfo));
and get it with JSON.parse.
score:0
A neat and clean solution to save the redux state even after refresh is Redux persist.
It works like a charm.
score:1
As Dan Abramov suggests you should use the local storage
in the store's subscribe
method:
store.subscribe(() => {
// persist your state
})
Before creating the store, read those persisted parts:
const persistedState = // ...
const store = createStore(reducer, persistedState)
If you use
combineReducers()
you’ll notice that reducers that haven’t received the state will “boot up” as normal using their defaultstate
argument value. This can be pretty handy.It is advisable that you debounce your subscriber so you don’t write to localStorage too fast, or you’ll have performance problems.
Finally, you can create a middleware that encapsulates that as an alternative, but I’d start with a subscriber because it’s a simpler solution and does the job well.
score:1
🎈 Shortly
Make this:
const initialState = {
user: {
id: localStorage.getItem('id') || '',
firstName: localStorage.getItem('firstName') || '',
secondName: localStorage.getItem('secondName') || '',
email: localStorage.getItem('email') || '',
isAuth: localStorage.getItem('token') ? true : false,
},
}
📿 A little bit complicated but extendable way
Create a middleware which will serve everything related to application persisting state. There you can save data to localStorage, cookie or IndexedDB. The middleware, let's call it LocalStoreMiddleware will listen same actions what your redux reducers do, when an action will be dispatched no matter where and by whom (Component, Saga, Socket) every middleware will do their responsible job, reducers will update redux store, LocalStoreMiddleware will save data to localStorage, cookie, indexDB and whatever.
The advantages
- no tight dependencies
- easy to extend
- one place for one domain business logic
- you make some elves happy from Narnia world
Create a file where you will store your functions related to persisting data
// local-store-resolvers.js
import {on} from './local-store-middleware.js'
function saveToken(action, state) {
localStorage.setItem('token', JSON.stringify(state.token));
}
function saveUsername(action) {
localStorage.setItem('username', JSON.stringify(action.username));
}
export default [
on(AUTHORIZATION, saveToken),
on(USERNAME_CHANGED, saveUsername),
]
Middleware factory
// local-store-middleware.js
export const on = (actionType, resolver) => (action, state) => (
actionType === action.type && resolver(action, state)
)
const createLocalStoreMiddleware = resolvers => store => next => action => {
resolvers.forEach(
resolver => resolver(action, store.getState())
)
return next(action)
}
export default createLocalStoreMiddleware
Redux store
// src/store/index.js - your main file where you create redux store
import createLocalStoreMiddleware from './local-store-middleware.js'
import resolvers from './local-store-resolvers.js'
const localStore = createLocalStoreMiddleware(resolvers)
const store = createStore(
combineReducers({users, someOtherReducer}),
applyMiddleware(localStore), // if you have more middlewares use compose
)
export default store
Source: stackoverflow.com
Related Query
- How to save Redux state properly after refreshing the page?
- How to save the response info in the Redux state after fetch into useEffect hook?
- redux state will become to the initial State after page reload NEXT.JS
- How to keep the current state of a page after a refresh? - React
- How to update persist redux state once after deploy the client side?
- How to properly set property(if user is logged) from cookie after page opens or F5 in React with router and redux
- How do I rerender the page after changing the state of a state variable?
- How to retain the state even after refreshing the browser the in reactjs?
- How to return previous state in Redux after we manipulate the state?
- I'd like to save the React local state to redux only when leaving the page
- Image with public URL from GCS won't display immediately after state update but works after refreshing the page
- How we can update the state of button to logout after successfull login in react redux
- React-Redux - How to redirect the page after storing the data in redux store?
- loading Data fetched from the API after refreshing page in react using redux
- How to properly display a product preview page after the product is created using react.js
- How to save information in the browser memory and display when pressed without refreshing the page using the react?
- How to maintain state after a page refresh in React.js?
- How to update the Redux store after Apollo GraphQL query returns
- Redux router - how to replay state after refresh?
- How do I use local state along with redux store state in the same react component?
- How do I call setState with the previous state plus an additional value in a redux connected controlled component?
- How to change the Redux state based on an Electron menu click?
- How to get the changed state after an async action, using React functional hooks
- How to clear the component stored redux state in componentWillUnmount?
- how and when to call a react component methods after state change from redux
- React Flash Message: How to make the message show without refreshing the page but refresh on 200
- ReactJS how to maintain State value when refreshing page
- How to wait after setting the state in react
- A component is changing the default value state of an uncontrolled Slider after being initialized. Material UI Slider with Redux State
- How to persist redux state in the easiest way?
More Query from same tag
- How to correctly set the swipe effect?
- Material-UI Drawer with Flexbox horizontal scroll not working on iOS Safari
- Can't log in with Laravel and ReactJS using custom REST API
- Am I Releasing my SQL Connection Correctly?
- how to access children props in React
- How to update the state when deleting an item using React-Redux and Rails api?
- .How to uninstall older version of npm manually from the windows for create-react app
- When I install any npm package in window this error occur and can not install package properly
- Formik and react-autocomplete
- how to handle null values while mapping JSON data in javascript
- How to make dashed line symbols (Polyline) using the polygonOptions (JS)
- React sending empty object instead of formData to API
- Sending multiple values to stored procedure and use it in IN operator
- Unable to create Stacked Grouped Bar Chart with chart.js / react-chartjs-2 in React
- how I call back function using reactjs
- This keyword is not pointing to the current object
- ReactJs change time video html5
- <Switch> component matching null value in react-router-4
- React, observer stateless component with typescript
- React routes param auto decode string
- How put and get states into localStorage in Redux
- Can't use React hooks in react-router-dom components
- In general is it better to use one or many useEffect hooks in a single component?
- React Pass Array Through Props
- Not able to add, update, delete rows in material table react using class based component. Previously it was working with functional component
- return function not rendering elements with js
- react/jquery: redirecting to another URL with built query string
- How to render HTML Template and bind data from JSON response in ReactJS?
- Using usestate hook with array when getting data from redux store
- Cannot configure webpack 2.2.1 correctly, keep throwing WebpackOptionsValidationError