Skip to content

mergeProps example will never shallowEqual #1302

Closed
@davidjbradshaw

Description

@davidjbradshaw

Do you want to request a feature or report a bug?

Documentation bug

What is the current behavior?

The example of mergeProps in the documentation creates a new function each time it is called, so the shallowEqual test will always fail leading to the component always rerendering.

This is the current example:

import * as actionCreators from './actionCreators'

function mapStateToProps(state) {
  return { todos: state.todos }
}

function mergeProps(stateProps, dispatchProps, ownProps) {
  return Object.assign({}, ownProps, {
    todos: stateProps.todos[ownProps.userId],
    addTodo: (text) => dispatchProps.addTodo(ownProps.userId, text)
  })
}

export default connect(mapStateToProps, actionCreators, mergeProps)(TodoApp)

What is the expected behavior?

I would expect the component to update only if ownProps.userId changes.

Suggested fix

If you're happy with this I can make a PR, but not sure if your happy to use Ramda in an example.

import { identity, memoizeWith } from 'ramda'
import * as actionCreators from './actionCreators'

const memoize = memoizeWith(identity)
const addTodo = memoize(
  (userId, dispatchProps) => (text) => dispatchProps.addTodo(userId, text)
)

function mapStateToProps(state) {
  return { todos: state.todos }
}

function mergeProps(stateProps, dispatchProps, ownProps) {
  return Object.assign({}, ownProps, {
    todos: stateProps.todos[ownProps.userId],
    addTodo: addTodo(ownProps.userId, dispatchProps)
  })
}

export default connect(mapStateToProps, actionCreators, mergeProps)(TodoApp)

Which versions of React, ReactDOM/React Native, Redux, and React Redux are you using? Which browser and OS are affected by this issue? Did this work in previous versions of React Redux?
7

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