Search code examples
reactjsreact-reduxredux-formreact-props

Can't use data from redux-form inside my component


I have a simple redux-form on the first page of my project and a button to the next page where I want to display the data from the form.

import React from 'react';
import { connect } from 'react-redux';

class UsersList extends React.Component {
    componentDidMount() {
        console.log(this.props.form.contact.values)
        // this displays the data
    }

    render(){
        let { firstName, lastName } = this.props.form.contact.values;
        // this doesn't display the data
        return (
            <div>
                <p>{firstName}</p>
                <p>{lastName}</p>
            </div>
        );
    };
};

function mapStateToProps(state) {
    return {
        form: state.form
    };
};

export default connect(mapStateToProps, null)(UsersList);

This is the component where I'm trying to display the data submitted through the form. As you can see in the comments, when I do "console.log(this.props.form.contact.values)" in the componentDidMount method, it works just fine, and I can see the info in the log, but when I try to use it to actually display stuff in the p tags, I get "Cannot read property 'values' of undefined" error.

I don't know it this is relevant, but when console.logging, I get the data in an object. I also tried to map over it inside the return, still without success.

Any help is appreciated!


Solution

  • This is normal because when you change route, the @@redux-form/DESTROY action will be called emptying all the data from your form and apparently from your form reducer, so this

    function mapStateToProps(state) {
        return {
            form: state.form
        };
    };
    

    will result to undefined. If you need to persist the form values, you need to tell your form not to destroy itself in unmount.

    reduxForm({
      destroyOnUnmount: false
    })(...)