Home > Software design >  How to pass setState into another function and use it to target value from material-ui select and ha
How to pass setState into another function and use it to target value from material-ui select and ha

Time:03-18

I am using a material ui select component, which is filled with data from an array with values and options.

In array there is also nested object prop called "setFilter". setFilter has a value of setState, which will be later used in handleFlilter.

  const [years, setYears] = useState("0");
  const [hours, setHours] = useState("");

  const inputs = [
    {
      name: "YEARS",
      propValue: years,
      setFilter: setYears,
      placeholder: "Years",
      selectOptions: optionsYears
    },
    {
      name: "AVAILABILITY",
      propValue: hours,
      setFilter: setHours,
      placeholder: "Availability",
      selectOptions: optionsHours
    }
  ];

  const handleFilter = (e, setFilter) => {
    setFilter(e.target.value);
  };

      <div>
        {inputs.map(
          ({ name, propValue, placeholder, selectOptions, setFilter }) => {
            return (
              <div>
                <CustomSelect
                  value={propValue}
                  onChange={handleFilter(setFilter)}
                >
                  {selectOptions.map((item) => (
                    <StyledOption key={item.option} value={item.value}>
                      {item.option}
                    </StyledOption>
                  ))}
                </CustomSelect>
              </div>
            );
          }
        )}

The problem is, i am getting an errors called "Cannot read properties of undefined (reading 'value')" or "e.target is undefined" in code sample.

Not sure where exactly is the problem. I am not targeting properly value, or the function is not correct ? Its not some normal html element like div, but a material select, so it should work with selected value prop.

I checked prop value, and the options are correctly visible in select list.

Here is the demo sample : https://codesandbox.io/s/unstyledselectcontrolled-material-demo-forked-wxqnrs?file=/demo.js:5335-5927

CodePudding user response:

There are two issues:

  1. You need to wrap your handler, if you want it to be fired onChange
  2. You need to pass e (the value) to the handerFilter handler

For example:

// Only changes to your code have been shown -- the rest was removed for brevity

...

const handleFilter = (e, setFilter) => {
  // Change: `e` in this case does not appear to be the event, but the value itself
  setFilter(e);
};

...

{/* Change: Wrapped Handler, passes e */}
<CustomSelect
  value={propValue}
  // Takes `e` and then passes that and setFilter to your handler
  onChange={(e) => handleFilter(e, setFilter)}
>
...

Working CodeSandbox: https://codesandbox.io/s/unstyledselectcontrolled-material-demo-forked-e49v8s

  • Related