I'm building a budget App using React 18 and Redux I don't know what is the problem here
import moment from "moment";
const filtersDefaultState = {
text: "",
sortBy: "date",
startDate: moment().startOf("month"),
endDate: moment().endOf("month"),
};
I got this problem after adding moment
redux-toolkit.esm.js?8bb3:444 A non-serializable value was detected in the state, in the path
Source code on Github: https://github.com/KhaledGharib/budgetApp
Trying to use DateRangePicker from react-dates
The issue here is that moment.js
date objects are not JSON serializable.
You can "serialize", e.g. stringify, the data yourself:
import moment from "moment";
const filtersDefaultState = {
text: "",
sortBy: "date",
startDate: moment().startOf("month").toISOString(true), // "2023-03-01T00:00:00.000Z"
endDate: moment().endOf("month").toISOString(true), // "2023-03-31T23:59:59.999Z"
};
You can alternatively decide to exclude this part of state in the serializability check if you really want to store non-serializable objects in the redux store via the serializabilityMiddleware:
import { configureStore, createSlice } from "@reduxjs/toolkit";
import expensesReducer from "../reducers/expenses";
import filtersReducer from "../reducers/filters";
const defaultMiddlewareConfig = {
serializableCheck: {
ignoredPaths: ["filters.startDate", "filters.endDate"],
}
};
export default () => {
const store = configureStore({
reducer: {
expenses: expensesReducer,
filters: filtersReducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware(defaultMiddlewareConfig),
});
return store;
};
You can serialize your startDate
and endDate
by adding toISOString()
function to it or if you are using redux-toolkit, simply set nonSerializableCheck
to false
.
const store = configureStore({
reducer: rootReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({serializableCheck:false}).concat(yourCustomMiddleWare),
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With