Edaurd B
Edaurd B

Reputation: 183

Why I get the Redux mutation Error and how can I avoid it?

I am using moment for some date utilities and I am storing the data in redux. After filling the form, searching the backend for the data, I get this error but I get it only the first time I search:

Error: Invariant failed: A state mutation was detected between dispatches, in the path 'app.departureDate._locale._longDateFormat.ll'.  This may cause incorrect behavior.

This is the reducer:

addDepartureDate(state, action) {
   return { ...state, departureDate: action.payload };
}

And here I use the data:

const {
    flightType, 
    localeConfig,
    departure,
    arrival,
    departureDate,
    arrivalDate,
    currency
} = useSelector(state => state.app);
const startDate = departureDate;

And the value is changed only when a new date is selected from react-dates but the error is not thrown then, I get the error after trying to get data from the backend.

Upvotes: 0

Views: 490

Answers (1)

markerikson
markerikson

Reputation: 67499

A moment instance is both mutable and not serializable, and thus shouldn't be kept in the Redux store:

Prefer keeping date values in the store as numeric timestamps or strings (ie, date.toISOString(), etc)

Upvotes: 1

Related Questions