Search code examples
reactjsreduxredux-formreselect

How to use redux-form with reselect


I want to use the reselect with redux-form to get the value from redux. the problem is I don't know how to combine the getFormValues with reselect. it seems that I cannot access the state in the createSelector. so that I cannot come up a way to use the redux-form's selector in the reselect.

For example:

// How to access the state here?
const getFoo = createSelector(
  [getBar],
  (bar) => {
    // return something
  }
)

The selector in redux works like this:

getFormValues('formName')(state);

Solution

  • You likely want to use reselect with redux-form's selectors (which are how you get current data out of redux-form).

    You can learn more about selectors here....

    https://redux-form.com/7.3.0/docs/api/formvalueselector.md/

    with an example here...

    https://redux-form.com/7.3.0/examples/selectingformvalues/

    You would then use a Reselect selector with a Redux-form selector sort of like this...

    const selector = formValueSelector('myForm');
    const mapStateToProps = createStructuredSelector({
      firstValue: (state) => selector(state, 'firstValue')
    });
    

    Here is another example of one being used from a different Github related subject https://github.com/erikras/redux-form/issues/1505

    const formSelector = formValueSelector('myForm')
    const myFieldTitle = (state) => formSelector(state, 'title')
    const doSomethingWithTitleSelector = createSelector(myFieldTitle, (title) => {
        return doSomethingWithTitle(title)
    })
    
    function doSomethingWithTitle() { ... }
    
    const Form = reduxForm({
        form: 'myForm',
    })(TheComponent)
    
    export default connect(
        state => ({
            titleWithSomethingDone: doSomethingWithTitleSelector(state)
        })
    )(Form)