Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep React components state after browser refresh

Thank you reading my first question.

I trying to auth With Shared Root use react, react-router and firebase. So, I want to keep App.js 's user state. but when I tried to refresh the browser, user state was not found.

I've tried to save to localstorage. But is there a way to keep state on component after browser refresh without localStorage?


App.js

import React, { Component, PropTypes } from 'react'
import Rebase from 're-base'

import auth from './config/auth'

const base = Rebase.createClass('https://myapp.firebaseio.com')

export default class App extends Component {
  constructor (props) {
    super(props)
    this.state = {
      loggedIn: auth.loggedIn(),
      user: {}
    }
  }

  _updateAuth (loggedIn, user) {
    this.setState({
      loggedIn: !!loggedIn,
      user: user
    })
  }

   componentWillMount () {
     auth.onChange = this._updateAuth.bind(this)
     auth.login() // save localStorage
   }

  render () {
    return (
      <div>
        { this.props.children &&
          React.cloneElement(this.props.children, {
            user: this.state.user
          })
        }
      </div>
    )
  }
}
App.propTypes = {
  children: PropTypes.any
}

auth.js

import Rebase from 're-base'
const base = Rebase.createClass('https://myapp.firebaseio.com')

export default {
  loggedIn () {
    return !!base.getAuth()
  },

  login (providers, cb) {
    if (Boolean(base.getAuth())) {
      this.onChange(true, this.getUser())
      return
    }

    // I think this is weird...
    if (!providers) {
      return
    }

    base.authWithOAuthPopup(providers, (err, authData) => {
      if (err) {
        console.log('Login Failed!', err)
      } else {
        console.log('Authenticated successfully with payload: ', authData)
        localStorage.setItem('user', JSON.stringify({
          name: base.getAuth()[providers].displayName,
          icon: base.getAuth()[providers].profileImageURL
        }))
        this.onChange(true, this.getUser())
        if (cb) { cb() }
      }
    })
  },
  logout (cb) {
    base.unauth()
    localStorage.clear()
    this.onChange(false, null)
    if (cb) { cb() }
  },
  onChange () {},
  getUser: function () { return JSON.parse(localStorage.getItem('user')) }
}

Login.js

import React, { Component } from 'react'
import auth from './config/auth.js'

export default class Login extends Component {
  constructor (props, context) {
    super(props)
  }

  _login (authType) {
    auth.login(authType, data => {
      this.context.router.replace('/authenticated')
    })
  }
  render () {
    return (
      <div className='login'>
        <button onClick={this._login.bind(this, 'twitter')}>Login with Twitter account</button>
        <button onClick={this._login.bind(this, 'facebook')}>Login with Facebook account</button>
      </div>
    )
  }
}
Login.contextTypes = {
  router: React.PropTypes.object.isRequired
}
like image 425
jinma Avatar asked May 12 '16 01:05

jinma


People also ask

How do I keep state on page refresh?

To maintain state after a page refresh in React, we can save the state in session storage. const Comp = () => { const [count, setCount] = useState(1); useEffect(() => { setCount(JSON. parse(window. sessionStorage.


1 Answers

If you reload the page through a browser refresh, your component tree and state will reset to initial state.

To restore a previous state after a page reload in browser, you have to

  • save state locally (localstorage/IndexedDB)
  • and/ or at server side to reload.

And build your page in such a way that on initialisation, a check is made for previously saved local state and/or server state, and if found, the previous state will be restored.

like image 176
wintvelt Avatar answered Oct 23 '22 12:10

wintvelt