Skip to content

Suggestion for with-redux example: using higher-order component to replace repeated codes. #1193

@huzidaha

Description

@huzidaha

The example of next.js with redux has repeated codes in every page, but wouldn't it be better to use higher-order component to replace this kind of repeated codes. For example:

next-connect.js:

import React, { Component, PropTypes } from 'react'
import { Provider, connect } from 'react-redux'
import { createStore, applyMiddleware } from 'redux'
import thunkMiddleware from 'redux-thunk'
import reducer from './reducer'

let store = null

const wrapWithProvider = (PageComponent) => class extends Component {
  static propTypes = {
    initialState: PropTypes.object
  }

  static async getInitialProps (ctx) {
    const { req } = ctx
    const isServer = !!req
    const props = PageComponent.getInitialProps ? await PageComponent.getInitialProps(ctx) : {}
    if (isServer && typeof window === 'undefined') {
      store = createStore(reducer, {}, applyMiddleware(thunkMiddleware))
      props.initialState = store.getState()
    }
    return props
  }

  constructor (props) {
    super(props)
    if (!store) {
      store = createStore(reducer, props.initialState, applyMiddleware(thunkMiddleware))
    }
  }

  render () {
    return (
      <Provider store={store}>
        <PageComponent {...this.props} />
      </Provider>
    )
  }
}

export default (mapStateToProps, mapDispatchToProps) => (PageComponent) => {
  PageComponent = connect(mapStateToProps, mapDispatchToProps)(PageComponent)
  return wrapWithProvider(PageComponent)
}

In every page you can easily use next-connect.js and connect to store like using redux normally:

index.js:

import nextConnect from './next-connect'

class Index extends Component {
  // ...
  render () {...}
}

export nextConnect((state) => state, null)(Index)

You can gain the same abilities like with-redux example does but with convenience.

Just a suggestion, feel free to close.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions