So I have a component in a multi page form, where I have a multiselect dropdown. So what I'm trying to achieve is data persistence in the multiselect dropdown while changing the pages of the form.
Here is my code:
import React, { useEffect, useState } from "react";
import Select from "react-select";
import makeAnimated from "react-select/animated";
import { HotelLists } from "./data";
import useFormContext from "../../hooks/useFormContext";
const animatedComponents = makeAnimated();
const MultiDropDown = ({
id,
label,
name,
options,
handleChange,
handleOptions,
nightOptions,
dValue,
}) => {
const { page, subPage, days } = useFormContext();
const [selectedOptions, setSelectedOptions] = useState([]);
console.log(page, subPage);
useEffect(() => {
console.log("in useEffect 1");
if (dValue) {
const value = options?.filter((option) => dValue.includes(option.value));
console.log(value);
setSelectedOptions(value);
}
}, []);
console.log(options, selectedOptions);
console.log("render");
useEffect(() => {
const selectedValues = selectedOptions.map((option) => option.value);
const remainingOptions =
selectedValues.length < 1
? nightOptions
: nightOptions &&
nightOptions.filter(
(option) => !selectedValues.includes(option.value)
);
handleOptions(remainingOptions);
selectedValues.length > 0 &&
handleChange(
{
value: selectedValues,
},
id,
name
);
}, [selectedOptions]);
// console.log(name)
const handleSelectChange = (value) => {
const selected = value;
setSelectedOptions(selected);
};
return (
<div className="w-full">
<label>{label}</label>
<Select
className="w-full mt-1"
closeMenuOnSelect={false}
components={animatedComponents}
isMulti
options={options}
value={selectedOptions}
type="multi"
onChange={(value) => {
handleSelectChange(value);
}}
/>
</div>
);
};
export default MultiDropDown;
The value of the multiselect dropdown is saved in the context using handleChange. When we come back to the page with the multiselect drowdown, the dValue is used to retrieve the data from the context and use as a default value in the dropdown. dValue is an array. So when this component is rendered, the first useEffect is not being called which results in the dropdown without the default Value . What Should I do?
I tried using the useEffect without a dependency array which works and the value shows in the dropdown but there is the infinite render issue, also I tries using dValue in dependency array, which also work, and the value shows up in the dropdown, but since the dValue is coming straight from the context and handleChange is changing the value of the dropdown on onChange, when I try to select other options in the dropdown it keeps calling the useEffect which results in empty dValue
Try this code and check :