Search code examples
reactjsreact-reduxredux-form

React-Redux initialize values that come from a reducer for a FIeldArray


I have a proof of content, you can see the whole thing here: https://codesandbox.io/s/87oyv8p89 … specifically containers/Form1.js

What I want to do here is grab a set of books from the reducer (eventually this will be populated by an API, but again this is a PoC). As part of this, I want to create a fieldarray with an array element for each book, and I want to default the value of the text field to the title of the book, what I tried is not working -- am I thinking about this wrong? is there a right way of doing this?

For posterity i have the following npm dependencies:

  • react
  • react-dom
  • react-redux
  • react-script
  • redux
  • redux-form

and the following files (see link above for ALL of the files):

src/containers/Form1.js

import React, { Component } from "react";
import { Field, reduxForm, FieldArray } from "redux-form";

import { connect } from "react-redux";

function fetchBooks() {
  return {
    type: "FETCH_BOOKS",
    payload: {} //placeholder
  };
}

class Form1 extends Component {
  componentDidMount() {}

  renderBooks = ({ fields, meta: { error, submitFailed } }) => {
    return (
      <ul>
        {this.props.books.map((book, index) => {
          return (
            <li key={index}>
              <Field
                name={`book[${index}].title`}
                label={`Title (should be ${book.title})`}
                component={this.renderField}
                defaultValue={book.title}
                type="text"
              />
            </li>
          );
        })}
      </ul>
    );
  };

  renderField = field => {
    const { meta } = field;

    const error = meta.touched && meta.error;
    let errorMsg = "";
    let formClasses = ["form-group"];
    if (error) {
      errorMsg = <small className="text-help">{meta.error}</small>;
      formClasses.push("has-danger");
    }

    let type = "text";
    if (field.type) {
      type = field.type;
    }

    let fieldElement = (
      <input className="form-control" type={type} {...field.input} />
    );

    return (
      <div className={formClasses.join(" ")}>
        <label>{field.label}</label>
        {fieldElement}

        {errorMsg}
      </div>
    );
  };

  onSubmit = values => {
    console.log(values);
  };

  render() {
    const { handleSubmit } = this.props;

    return (
      <form onSubmit={handleSubmit(this.onSubmit)}>
        <FieldArray name="books" component={this.renderBooks} />
        <button type="submit" className="btn btn-primary">
          Submit
        </button>
      </form>
    );
  }
}

function validate(values) {
  const errors = {};

  return errors;
}

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

export default reduxForm({
  validate,

  form: "FormWrapper",
  destroyOnUnmount: false,
  forceUnregisterOnUnmount: true
})(connect(mapStateToProps, { fetchBooks })(Form1));

src/reducers/index.js

import { combineReducers } from "redux";
import { reducer as formReducer } from "redux-form";
import books from "./books";

const rootReducer = combineReducers({
  form: formReducer,
  books: books
});

export default rootReducer;

src/reducers/books.js

export default function(state = null, action) {
  if (!state) {
    state = [
      {
        title: "Things Fall Apart",
        author: "Chinua Achebe",
        isbn: "9782330070403"
      },
      {
        title: "A Brave New World",
        author: "Aldous Huxley",
        isbn: "9781405880275"
      },
      {
        title: "Starship Troopers",
        author: "Robert Heinlein",
        isbn: "9782290301296"
      }
    ];
  }

  switch (action.type) {
    default:
      return state;
      break;
  }
}

Solution

  • This is a fairly simple fix!

    Updating the componentDidMount on the Form1 component sets the data as expected

    componentDidMount() {
        const { books, initialize } = this.props;
        initialize({ books });
    }