Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to persisting data in a react/redux web app?

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?

like image 932
totalnoob Avatar asked Aug 28 '18 19:08

totalnoob


1 Answers

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

like image 127
ageoff Avatar answered Oct 03 '22 23:10

ageoff