I am using react-multi-date-picker to create an exemptions scheduler. The react-multi-date-picker is used inside of a react-table as follows:
const [data, setData] = useState(0);
const [dateValues, setDateValues] = useState({});
const columns = useMemo(
() => [
{
Header: "Exemptions",
// First group columns
columns: [
{
Header: "Exemptions",
accessor: "exemptions",
Cell: ({ row, data }) => (
<DatePicker
multiple
key={data[row.index].id}
onChange={(dateValues) => {
const valueId = data[row.index].id;
Object.keys(dateValues).map((key) => {
setDateValues((oldArray) => ({
...oldArray,
[valueId]: {
...oldArray[valueId],
[key]: dateValues[key]
?.toDate?.()
.toISOString?.()
.substring?.(0, 10),
},
}));
});
}}
plugins={[<DatePanel />]}
/>
),
},
],
},
],
[]
);
data produces an object from an axios call with the following structure.
(1) [{…}]
0:
exemptions: null
id: 1
name: "John Smith"
user_supervisor: "Joe Black"
[[Prototype]]: Object
If I were to select 4 dates from the react-multi-date-picker and after my onChange call in the memoization hook, I am left with this in the dateValues:
{1: {…}}
1:
0: "2022-02-02"
1: "2022-02-03"
2: "2022-02-08"
3: "2022-02-08"
[[Prototype]]: Object
[[Prototype]]: Object
This all works as expected. What I am struggling with is removing dates from the dateValues object when a user deselects the date from the react-multi-date-picker. I have tried using a ternary, I have tried using .filter
and .includes
. Every option I have tried throws a different error.
I am at a mental block on the logic needed. My thoughts have been I need to compare the previous state with the new state and keep matching values while discarding any values that don't match between the two states. I just can't code it in a way that works. Any help on this would be much appreciated.
if you were using filter on the dateValues the error was thrown most probably because you were trying to use that method on an object. you can use the filter method on arrays but not ob objects. Try to convert dateValues to an array with Object.values(obj) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values
and then chain the filter on it. Filter all the dates that are not equal to the deselected date and update the state with the result array coming from the filter method.