Search code examples
reactjsreduxredux-form

Inititial form values get discarded after adding/removing the form


I have a NotificationList component that renders NotificationCard from fetched data stored in a list.

//NotificatitonList.js
return this.props.notifications.list.map(n => {
  return (
    <div>
      <NotificationCard
        key={n.id}
        form={`updateNotification_${n.id}`}
        initialValues={n}
        notfId={n.id}
      />
    </div>
  );
});

NotificationCard contains a redux-form with unique name

form={'updateNotification_${n.id}'} and initial values initialValues={n}.

Relevant part of NotificationCard.js:

const formWrapperd = reduxForm({
  validate
})(NotificationCard);

export default connect(
  null,
  { someActions }
)(formWrapperd);

It works. But if I try to add new nofication to the top of notifications.list which is stored in redux, It gets added but all the initial values in my forms gets discarded too. If I add new notification to the end of the list, it works fine. The same goes for deleting notifications, it only works fine if you delete the last one in the list. I don't get why that happens, I don't seem to use list index anywhere.

Relevant part of the reducer:

const INITIAL_STATE = {list: [], ...};    

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    ...
    case CREATE_NOTIFICATION:
      return { ...state, list: [...state.list, action.payload] };
    case DELETE_NOTIFICATION:
        return {
          ...state,
          list: state.list.filter(el => el.id !== action.id)
        };

Thank you. Any ideas?

To make you understand better what I have: enter image description here


Solution

  • Managed to got it working by using initialize action creator that is passed as a prop by redux-form. Just put it in the componentDidMount with the initial values:

      componentDidMount() {
        this.props.initialize(this.props.initialValues);
      }