question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Difference between client and server state

See original GitHub issue

My client state only consists of the default arguments passed to each individual reducer. Cannot get it to match server state. What am I messing up here? Let me know if you need to see any more files.

store/index.js

import { createStore, applyMiddleware, compose } from 'redux'
import { composeWithDevTools } from 'redux-devtools-extension'
import thunk from 'redux-thunk'
import rootReducer from '../reducers'
import { createLogger } from 'redux-logger'
import withRedux from 'next-redux-wrapper'

const middleware = [thunk]

if (process.env.NODE_ENV === 'development') {
  // middleware.push(createLogger())
}

function initStore() {
  return createStore(rootReducer, composeWithDevTools(applyMiddleware(...middleware)))
}

export default initStore

pages/index.js

import React from 'react'
import defaultPage from '../hocs/defaultPage'
import NotAuthenticated from '~/NotAuthenticated'

function Index ({ isAuthenticated, children }) {
  if (isAuthenticated) {
    return (
      <div>
        { children }
      </div>
    )
  } else {
    return ( 
      <div>
        <NotAuthenticated/>
      </div>
    )
  }
}

export default defaultPage(Index)

hocs/defaultPage.js

import React from 'react'
import { getUserFromCookie, getUserFromLocalStorage } from '../utils/auth'
import initStore from '../store'
import saveUserAgent from '!/saveUserAgent'
import saveCurrentPage from '!/saveCurrentPage'
import withRedux from 'next-redux-wrapper'
import getMuiTheme from 'material-ui/styles/getMuiTheme'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'
import PropTypes from 'prop-types'
import NProgress from 'nprogress'
import Router from 'next/router'
import DesktopNavbar from '~/DesktopNavbar'
import Filters from '~/Filters'
import WidgetArea from '~/WidgetArea'
import saveWidgetConfig from '!/saveWidgetConfig' // only dispatch if diff in future
import styled, { ThemeProvider } from 'styled-components'
import defaultTheme from '../themes/default.theme'
import fetchUserData from '../actions/actionCreators/fetchUserData';
import _ from 'lodash'

const Container = styled.div`
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
`;

Router.onRouteChangeStart = (url) => {
  NProgress.start()
}
Router.onRouteChangeComplete = () => NProgress.done()
Router.onRouteChangeError = () => NProgress.done()

function wrapInAuthAndMaterialUI (Page) {
  class DefaultPage extends React.Component {
    static async getInitialProps (ctx) {
      const loggedUser = process.browser ? getUserFromLocalStorage() : getUserFromCookie(ctx.req);
      const pageProps = Page.getInitialProps && Page.getInitialProps(ctx);
      const { store, isServer, pathname } = ctx;
      const initPageProps = {
        ...pageProps,
        loggedUser,
        currentUrl: pathname,
        isAuthenticated: !!loggedUser,
        userAgent: store.getState().userAgent
      };
      return new Promise((resolve) => {
        store.dispatch(fetchUserData())
          .then(() => {
            resolve(initPageProps)
          })
      })
    }
    
    constructor (props) {
      super(props)
      this.logout = this.logout.bind(this)
    }

    getChildContext() {
      return { muiTheme: getMuiTheme({ userAgent: this.props.userAgent }) };
    }

    logout (eve) {
      if (eve.key === 'logout') {
        Router.push(`/?logout=${eve.newValue}`)
      }
    }

    componentDidMount() {
      window.addEventListener('storage', this.logout, false)
    }

    componentWillUnmount() {
      window.removeEventListener('storage', this.logout, false)
    }

    render () {
      // console.log('hocprops', this.props)
      return (
        <ThemeProvider theme={defaultTheme}>
          <MuiThemeProvider muiTheme={ getMuiTheme({ userAgent: this.props.userAgent }) }>
            <Container>
              <Page { ...this.props }>
                <DesktopNavbar/>
                <Filters/>
                <WidgetArea/>
              </Page>
            </Container>
          </MuiThemeProvider>
        </ThemeProvider>
      )
    }
  }
  DefaultPage.childContextTypes = {
    muiTheme: PropTypes.object,
  }
  
  return withRedux(initStore)(DefaultPage)
}

export default wrapInAuthAndMaterialUI

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
kirill-konshincommented, Nov 26, 2017

Seems that your init store does not take initialState parameter, should be const makeStore = (initialState, options) => {.

0reactions
thetoxicavengercommented, Nov 28, 2017

Wonderful. Thanks!

Sent from my iPhone

On Nov 28, 2017, at 2:02 PM, Kirill Konshin notifications@github.com wrote:

There’s no need to provide default state here, it should be assembled from your reducers. Just leave it undefined.

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub, or mute the thread.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Break up ReactJS application State into Types | bobbyhadz
The server state is asynchronous state that's stored on the server (i.e. products, orders) - we cache it on the client for performance...
Read more >
How to manage server and client state in a web application
In this article we talk about state in a react application and specially the differences between client-side and server-side state.
Read more >
Client-side vs. Server-side - Educative.io
Client-side means that the processing takes place on the user's computer. It requires browsers to run the scripts on the client machine without...
Read more >
What do client side and server side mean? - Cloudflare
Client side and server side describe where web application code runs. Learn more about client-side vs. server-side processes and client-side scripting.
Read more >
Difference Between Client and Server - Pediaa.Com
The difference between client and server is that a client is a machine or a program that requests for services through the web...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found