I'm creating a simple react/redux web app where you can simply enter a username and it'd kinda log you in to a dashboard view with that data. no login mechanisms or a need for session cookies or jwt tokens, just a basic app to learn how single page applications flow with react/redux.
the flow goes like this (with react router)
login page (/login) ->
enter username ->
handle submit ->
fetch data ->
populate redux store ->
redirect to dashboard component (/dashboard) ->
render data
class Login extends React.Component {
handleSubmit = event => {
this.props.getData(this.state.username)
}
render() {
.....
if (data !== '' && data.username !== '') {
return <Redirect to='/account'/>;
}
.....
}
}
class Account extends React.Component {
componentDidMount() {
if (!sessionStorage.username) {
sessionStorage.username = this.props.data.username;
} else {
this.props.getAddressInformation(sessionStorage.username)
}
}
.....
What I'm unsure of is how to best approach the issue where someone reloads the dashboard page for whatever reason and the state is gone. For now I'm just using session storage to save the username and on render of the account component / page, it checks for it and fetches the data back into the store.
is this a better way of doing this in terms of persisting the username and fetching the user data? is this the wrong way of doing this to begin with?
https://github.com/rt2zz/redux-persist
redux-persist will handle all of this for you.
From the readme:
// configureStore.js
import { createStore } from 'redux'
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage' // defaults to localStorage for web and AsyncStorage for react-native
import rootReducer from './reducers'
const persistConfig = {
key: 'root',
storage,
}
const persistedReducer = persistReducer(persistConfig, rootReducer)
export default () => {
let store = createStore(persistedReducer)
let persistor = persistStore(store)
return { store, persistor }
}
And the App.js
import { PersistGate } from 'redux-persist/integration/react'
// ... normal setup, create store and persistor, import components etc.
const App = () => {
return (
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<RootComponent />
</PersistGate>
</Provider>
);
};
If you need to do anything special before loading the state then you can use the onBeforeLift on the PersistGate
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With