Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 361
leuction Avatar asked Mar 06 '18 00:03

leuction


2 Answers

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)
like image 69
Shawn Matthews Avatar answered Sep 23 '22 13:09

Shawn Matthews


You can make use of getFormValues like so:

import { createSelector } from 'reselect';
import { getFormValues } from 'redux-form';

const selectFormValues = () => createSelector(
  (state) => state,
  (state) => getFormValues('formName')(state)
);
like image 28
Avasyu Avatar answered Sep 22 '22 13:09

Avasyu