Shorn Jacob
Shorn Jacob

Reputation: 1251

How to properly display a Material UI Native select and change the selection using a state hook

Code SandBox Here https://codesandbox.io/s/wild-brook-jpeio?file=/src/App.js

I acquire an array of values using useEffect hook. The array variable is set using useState hook

The value and onChange attributes of Native Select also uses another state variable and its set function to update it.

Using the below part of code to use the set function to set the selected value of the Native Select just after the useEffect gets the data.

 // set the default selection on first load
  if (!isEmpty(combolist)) {
    console.log(combolist[0].name);
    setSelection(combolist[0].name);
  }

But this is giving too many renders error.

How to fix this and achieve my objective

Upvotes: 0

Views: 642

Answers (2)

Taghi Khavari
Taghi Khavari

Reputation: 6582

you need to use a useEffect hook for that like this:


  useEffect(() => {
    if (data.length) {
      const combolist = data.map((obj) => pick(obj, ["id", "name"]));

      // set the default selection on first load
      if (!isEmpty(combolist)) {
        console.log(combolist[0].name);
        setSelection(combolist[0].name);
      }
    }
  }, [data]);

Upvotes: 1

bcjohn
bcjohn

Reputation: 2523

One easy way is move the set the combolist in useEffect to prevent the multiple re-render.

This is the solution link.

Upvotes: 1

Related Questions