Home > Software design >  React state value transfer to another state without repeating value?
React state value transfer to another state without repeating value?

Time:11-13

I am using the react-select library for multi-select. I am using it as a state selector but the problem is the react-select an array of objects. Like

{
        "label": "Andaman and Nicobar Islands",
        "value": "Andaman and Nicobar Islands"
    },
    {
        "label": "Andhra Pradesh",
        "value": "Andhra Pradesh"
    },

I want to extract the value part from it and I tried directly but It gave me an error I decided to use a different state array to extract but the problem is I only accept three state values and also want to remove duplicate values new state also have only values. I couldn't fix this problem help me to fix this.

const [job_preference, setJobPreference] =
        useState([]);
    const [multiSelect, setMultiSelect] = useState(
        []
    );

const handleMultiSelectChange = (val) => {
        setMultiSelect(val);
    };

const handleJobPreference = () => {
        multiSelect?.map((select) =>
            setJobPreference((prev) => [
                ...prev,
                select.value,
            ])
        );
    };

<div className='mb-3'>
                                    <label className='form-label'>
                                        Job Preference
                                    </label>
                                    <Select
                                        value={multiSelect}
                                        isMulti
                                        components={
                                            animatedComponents
                                        }
                                        isSearchable
                                        placeholder='Choose any 3 states as job location'
                                        options={states}
                                        onChange={
                                            handleMultiSelectChange
                                        }
                                        isOptionDisabled={() =>
                                            multiSelect.length >= 3
                                        }
                                    />
                                </div>

CodePudding user response:

To get the values onChange of multiselect you can do as

  const handleMultiChange = (options) => {
    const values = options.map((opt) => opt.value);
    console.log(values);
  };

CodePudding user response:

I think this will work for your needs to change slightly KcH answers.

const handleMultiSelectChange = (options) => {
        setMultiSelect(options);
        const values = options.map(
            (opt) => opt.value
        );
        setJobPreference([...values]);
    };
  • Related