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.

gitInitialProps not available when using Redux-Form

See original GitHub issue

I have a component using redux-from and I’m trying to setup a url route to pass params to edit the object Im passing to it. When I remove the redux-form from the component, getInitialProps works.

Here is my current component:

import React from 'react'
import { initStore } from '../store'
import withRedux from 'next-redux-wrapper'
import { bindActionCreators } from 'redux'
import standardLayout from '../hocs/standardLayout'
import { Field, reduxForm } from 'redux-form'
import checkBox from '../components/inputs/checkbox'
import renderField from '../components/inputs/renderField'
import env from '../config/envConfig'
import { addStore } from '../actions/storesActions'
import { toastr } from 'react-redux-toastr'
import Router from 'next/router'

class addStoreForm extends React.Component {
  static getInitialProps ({ store, res, query }) {
    console.log('query from HOC')
    // console.log(query)
    const post = 'string'

    return { post }
  }

  constructor (props, context) {
    super(props, context)
    this.handleFormSubmit = this.handleFormSubmit.bind(this)
    this.edit = false
    //query setup for edit or add page
    const params = this.props.url.query
    if (params.id) {
      this.edit = true
    }
  }

  componentDidMount () {
    console.log('CDM')
  }

  handleFormSubmit (formProps) {
    this.props
      .addStore(formProps)
      .then(r => {
        toastr.success('Saved', 'Store Saved Successfully!')
        Router.push(`/store?params=${r.slug}`, `/store/${r.slug}`)
      })
      .catch(e => {
        toastr.error('Error:', e)
      })
  }

  render () {
    const { handleSubmit, valid, errorMessage } = this.props
    return (
      <div className='inner'>
        <h2>{this.edit ? 'Edit Store' : 'Add Store'}</h2>
        <form
          className='card'
          onSubmit={handleSubmit(this.handleFormSubmit)}
          encType='multipart/form-data'
        >
          <Field
            name='name'
            type='text'
            component={renderField}
            label='Name:'
          />
          <label htmlFor='description'>Description</label>
          <Field name='description' component='textarea' label='Description:' />
          <ul className='tags'>
            {env.TAGS.map(tag => (
              <Field
                key={tag}
                value={tag}
                name={`tags.[${tag}]`}
                id={tag.toLowerCase().replace(' ', '_')}
                type='checkbox'
                component={checkBox}
                label={tag}
              />
            ))}
          </ul>

          <input
            type='submit'
            className='button'
            value='Save'
            disabled={valid === false ? 'disabled' : ''}
          />

        </form>

      </div>
    )
  }
}

const validate = values => {
  const errors = {}

  if (!values.name) {
    errors.name = 'Required'
  }

  return errors
}

const editStore = reduxForm({
  form: 'signin',
  validate
})(addStoreForm)

const mapDispatchToProps = dispatch => {
  return {
    addStore: bindActionCreators(addStore, dispatch)
  }
}

export default withRedux(initStore, null, mapDispatchToProps)(
  standardLayout(editStore, 'Edit Store')
)

Issue Analytics

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

github_iconTop GitHub Comments

2reactions
AugustinLFcommented, May 12, 2017

@spencersmb My guess, if I’m not mistaking (went trough similar things) is that next tries to call the getInitialProps of the exposed component, but reduxForm doesn’t call yout static method. The solution is usually to move the getInitialProps declaration to a higher component, such as standardLayout, or if this hoc does call the base component getInitialProps manually, to the editStore component.

You would end up with something like:

const editStore = reduxForm({
  form: 'signin',
  validate
})(addStoreForm)

editStore.getInitialProps = ({ store, res, query }) {
    console.log('query from HOC')
    // console.log(query)
    const post = 'string'

    return { post }
  }

But for this to work, you need to make sure that standardLayout does declare its own getInitialProps, and calls the wrapped component’s own getInitialProps (that is actually something that withRedux does):

const standardLayout = BaseComponent => {
    // The hoc declaration
    static async getInitialProps(context) {
           
        const childProps = typeof BaseComponent.getInitialProps === 'function'
            ? await BaseComponent.getInitialProps(context)
            : {};
        return {
            ...childProps,
           ...{}, // whatever standardLayout wants to add
            };
    }
}

This last example is inspired by the use of HOC by an example, see for instance how they use getInitialProps to inject some data, while leaving to the page component the ability to expose its own getInitialProps

1reaction
timneutkenscommented, May 12, 2017

That’s exactly the case. getInitialProps is called on the exposed component. So a HOC has to be aware of Next.js to properly call getInitialProps and pass the props through.

Read more comments on GitHub >

github_iconTop Results From Across the Web

getInitialProps doesn't seem to work when using Next.js with ...
I was able to fetch data from server from getInitialProps function but after wrapping my _app.js with next-redux-wrapper the getInitialProps ...
Read more >
getInitialProps - Data Fetching - Next.js
This new directory has support for colocated data fetching at the component level, using the new React use hook and an extended fetch...
Read more >
reduxForm(config:Object)
a function that takes all the form values, the dispatch function, the props given to your component and the current blurred field, and...
Read more >
How to initialize the redux-form with values from store-Reactjs
Coding example for the question How to initialize the redux-form with values ... Then get the response from redux store while in the...
Read more >
Data fetching in React and Next.js with useSWR to impress ...
We all can agree: there are many ways to fetch data in Next.js app. Because of that, people at the parties are not...
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