Sachin Karia
Sachin Karia

Reputation: 565

Redux 'connect' not detecting state array changes

I have setup redux with a reducer that updates an array of time slots for a given date. Every time I change the date, the reducer updates the state (I have console logged the state change which happens as expected in my mapStateToProps function), however, the redux connect function doesn't detect that the array of time slots has been updated. Here is my reducer:

import { SHOW_ERROR, HIDE_ERROR, SHOW_SUCCESS, HIDE_SUCCESS, UPDATE_TIME_SLOTS } from '../actions/types';

const INITIAL_STATE = { error: null, success: null, timeSlots: null };

export default function (state = INITIAL_STATE, action) {
  switch (action.type) {
    case SHOW_ERROR:
      return { ...state, error: action.payload };
    case HIDE_ERROR:
      return { ...state, error: action.payload };
    case SHOW_SUCCESS:
      return { ...state, success: action.payload };
    case HIDE_SUCCESS:
      return { ...state, success: action.payload };
    case UPDATE_TIME_SLOTS:
      return { ...state, timeSlots: action.payload };
    default:
      break;
  }
  return state;
}

The time slots is always an array like so:

["08:30", "09:15", "10:00", "10:45", "11:30", "12:15", "13:00", "13:45", "14:30", "15:15", "16:00", "16:45"]

Here is my mapStateToProps function which then uses redux connect to send these props to my BookingForm (this is where my console.log detects the change in state correctly:

function mapStateToProps(state) {
  console.log(state.public.timeSlots);
  return {
    timeSlots: state.public.timeSlots
  };
}

export default connect(mapStateToProps, { create, getAvailableSlots })(form(BookingForm));

Every time I click on a date in my form the state is updated with the new array, however, my connect function doesn't detect this update and therefore the BookingForm component doesn't re-render. I am assuming this is to do with the array not immutably being updated, however, I haven't found a solution to designing it so that it is updated immutably.

Any help?

Upvotes: 1

Views: 1865

Answers (1)

gilamran
gilamran

Reputation: 7294

You are probably sending the same array instance, and the connect function is checking for reference changes only! btw: same for objects.

Using the same array will not get detected by the connect, you have to create a new array every time you want to update the state.

How about you let the reducer deal with that? So, once the user clicks a date on your form, send an action to record that, say "DATE_CLICKED" action, and in the reducer, add the date to a new array along with all the previous values.

Like this:

  return [...state.dates, action.date]

Upvotes: 4

Related Questions