State not updating when using select and options

Viewed 174

a bit new to this still. I have a select with dropdown options and am trying to update the 'levels' state when the option of the list changes. When I change the levels state manually it re-renders but not when using the onChange function of the select. Thanks.

  function App() {
  const [color, setColor] = useState("");
  const [error, setError] = useState(false);
  const [levels, setLevels] = useState(10);
  const [list, setList] = useState(new Values('#245422').all(levels));
  

  const handleSubmit = (e) => {
    e.preventDefault();
    try {
      let colors = new Values(color).all(levels);
      setList(colors);
    } catch (error) {
      setError(true);
      console.log("please enter valid color");
    }
  };
  
  return (
    <>
      <section className="container">
        <h3>color generator</h3>
        <form onSubmit={handleSubmit}>
          <input
            type="text"
            value={color}
            onChange={(e) => setColor(e.target.value)}
            placeholder="#ff34sd"
            className={`${error ? "error" : null}`}
          />
          <button className="btn" type="submit">
            submit
          </button>
        </form>
        <div>
      <label htmlFor="variation" className="select-label">
        # of variations
      </label>
      <select name="variation" id="variation" onChange={(e) => {
        const selectValue = parseInt(e.target.value)
        setLevels(selectValue)
        console.log(selectValue)
      }}>
        <option value="26" default>7</option>
        <option value="10">21</option>
        <option value="6">32</option>
        <option value="4">51</option>
        <option value='2'>101</option>
      </select>

    </div>
2 Answers

Thanks for your assistance I figured out that I needed to update the list rather than the levels, if that makes sense, here is what I did to make it work.

<select name="variation" id="variation" onChange={(e) => {
        const selectValue = parseInt(e.target.value)
        setList(new Values(`${color}`).all(selectValue))
      }}>
        <option value="26" default>7</option>
        <option value="10">21</option>
        <option value="6">32</option>
        <option value="4">51</option>
        <option value='2'>101</option>
      </select>

I think, you have forgotten to use value attribute:

<select value={levels.toString()} name="variation" id="variation" onChange={(e) => {
        const selectValue = parseInt(e.target.value)
        setLevels(selectValue)
        console.log(selectValue)
      }}>
        <option value="26" default>7</option>
        <option value="10">21</option>
        <option value="6">32</option>
        <option value="4">51</option>
        <option value='2'>101</option>
      </select>
Related