0

What I've been trying is t get a value from formReducer in a container component.

There are two component. One is a presentational component with Redux-Form.

class Form extends React.Component {
    render() {
        return (
        <div>
            <form onSubmit={handleSubmit}>
            <Field name="title"
                   component="input"
                    type="text"/>
            </form>
        </div>
        )
    }
}

Form = reduxForm({
    form: 'PostEditor',
    enableReinitialize: true,
})(Form);

Form = connect(
    state => ({
        initialValues: state.post.post,
        enableReinitialize: true,
    }),
)(Form)

export default Form;

And the other is its container, which is where I'd like to access formReducer.

class PostEditor extends React.Component {
    render() {
        console.log("form", this.props.PostEditor);//This results in "undefined"
        return (<Form onSubmit={data=> this.handleSubmit(data)}/>);
    }
}

const mapStateToProps = (state) => {
    return {
        PostEditor: state.form
    }
}
export default connect(mapStateToProps, null)(PostEditor);

In Redux' store, form reducer is set to be state.form, but this cannot be accessed.

Is it possible to get values from the reducer?

Hiroki
  • 3,893
  • 13
  • 51
  • 90

2 Answers2

1

Try to use one of ReduxForm selectors.

import { getFormValues } from 'redux-form';

const mapStateToProps = (state) => {
    return {
        PostEditor: getFormValues('PostEditor')(state)
    }
}

Here you have detailed documentation: https://redux-form.com/7.2.0/docs/api/selectors.md/

Sławomir Rosiek
  • 4,038
  • 3
  • 25
  • 43
1

To access the values of a form import the following selector from redux-form

import { formValueSelector } from 'redux-form';

Then call the function with the name of the form you wish to retrieve the values of in mapStateToProps.

This will return a function which is then called with the state of the Redux store as well as the name of the field for which we wish to obtain the value.

const mapStateToProps = (state) => {
    return {
        titleFieldValue: formValueSelector('PostEditor')(state, 'title')
    }
}

We can also add in more arguments to this function call if we wish to retrieve multiple fields. For example

formValueSelector('PostEditor')(state, 'title', 'name', 'otherField')

The following syntax is an example of a "curried" function. This is just a name given to functions that return other functions. If you are interested read this for an introduction to currying.

therewillbecode
  • 7,090
  • 4
  • 35
  • 42