简体   繁体   中英

onChange react-select not calling my function

I have the following react-select code which all works fine and sets my Formik state values.

  const [selectedOptions, setSelectedOptions] = useState([]);  

    <Select
        options={myOptions}
        isMulti={true}
        name={`myGroups.${index}.selectedOptions`}
        onChange={(selectedOptions) => {
            let e = { target: { name: `myGroups.${index}.selectedOptions`, value: selectedOptions } };
            handleChange(e);
            handleChangeIndex(index);
        }}
    />

My question is, during the onChange I also want to call another function: handleChangeIndex to set state values, ie:

  const handleChangeIndex = index => selectedOption => {
    console.log("inside handleChangeIndex....")
    const optionsCopy = [...selectedOptions];
    optionsCopy[index] = selectedOption;

    setSelectedOptions(optionsCopy);
  };  

In my <Select> above, my function handleChangeIndex(index) is not being called as I am not seeing a console.log message but if I call the <Select> as follows with just my handleChangeIndex alone it works.

    <Select
        options={myOptions}
        isMulti={true}
        name={`myGroups.${index}.selectedOptions`}
        onChange={handleChangeIndex(index)}
    />

Can people pls assist with how to call my function as in the top <Select>

When you pass handleChangeIndex into Select directly, you are calling the function, which is returning another function ( currying ). Then Select is calling that new inner function when the values change.

When you call handleChangeIndex directly in the onChange in the first example you gave, you are only calling it once, which means you are getting that inner function, and then doing nothing with it.

If you then call that inner function with the selectedOptions , then it should work fine.

  const [selectedOptions, setSelectedOptions] = useState([]);  

    <Select
        options={myOptions}
        isMulti={true}
        name={`myGroups.${index}.selectedOptions`}
        onChange={(selectedOptions) => {
            let e = { target: { name: `myGroups.${index}.selectedOptions`, value: selectedOptions } };
            handleChange(e);
            handleChangeIndex(index)(selectedOptions);
        }}
    />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM