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

3

6

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?

Paulpaula answered 28/8, 2018 at 19:56 Comment(4)
why don't you use localStorage ?Jarietta
I've used that too.Paulpaula
so what's the issue with it?Jarietta
I just want to be sure there isn't a more efficient way of doing what I'm trying to achieve, or a better way of persisting the username.Paulpaula
S
5

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

Selfpity answered 28/8, 2018 at 20:18 Comment(0)
J
3

There are two ways to persist data: Cookies and LocalStorage

But here comes the distinction and their use cases:

  • We store data in cookies for server side reading and for client side we use localStorage.
  • If you're reading data in client side then don't use cookies as it consume some extra bandwidth in network calls.
  • LocalStorage has no expiry and you control in your app whenever you want to expire it.
  • LocalStorage is as big as 10MB per origin in Chrome but at least 5MB in some browsers while cookies can store upto 4096bytes.

It is all depend in your use case. I would recommend to use localStorage as you;re using it in your client side.

PS I won't recommend to use any persisting library. It will increase your app size. When it comes to code splitting and caching, then it becomes quite cumbersome to alleviate from these extra KBs. It happens when your app size grows. Remember don't go for extra packages unless you can't achieve the goal easily yourself.

Jarietta answered 28/8, 2018 at 20:11 Comment(0)
S
1

You should store and persist Username in Redux store and every time when starting the App you can access to Username from everywhere of App.

to persist redux state I recommend you redux-persist.

Schiffman answered 28/8, 2018 at 20:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.