-1

I have a select that works fine but I need to capture the value that I am selecting, but it is generating an error Cannot read properties of undefined (reading 'value'), i have not been able to solve it.

import React, { useState, useEffect } from "react";
import WindowedSelect from "react-windowed-select";

function App() {
  const [t4t, setUniversidad] = useState([]);
  const [e2, setE2] = useState(null);

  console.log(e2 + " Seleccionado");

  useEffect(() => {
    (async () => {
      const req = await fetch(
        `https://witalenco.com.co/apiWittytalent/dyc/titulos/carreras.php`
      );
      const getres2 = await req.json();
      console.log({ getres2 });
      setUniversidad(await getres2);
    })();
  }, []);

  // Here is the transformation
  const options = t4t.map((item) => ({
    label: item.carrera,
    value: item.id_titulos
  }));

  const handlecountrye2 = (event) => {
    setE2(event.target.value);
  };

  return (
    <div>
      <div class="col-12">
        <br />

        <WindowedSelect
          options={options}
          onChange={handlecountrye2}
          value={e2}
          name="e2"
        />
      </div>
    </div>
  );
}
export default App;

https://codesandbox.io/s/dreamy-darkness-9z9cck?file=/src/App.js:0-992

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Giovanny
  • 131
  • 12

1 Answers1

0

Note that this isn't strictly "a select", this is specifically react-windowed-select. So if you're following examples used for something like a <select> then you may be providing yourself with incorrect information.

If event.target is undefined then what is event? Logging it to the console reveals the following structure:

{label: "ABOGADO (A)", value: "3"}

(Which also suggests that it's been given a misleading name. It's not really an "event", more of a selected option. I would recommend renaming the variable in that function to something which reflects this.)

As you can see, there is indeed no target property there. So what property do you want to use? It looks like you want to use the whole object:

setE2(event);

I've forked your sandbox demo to demonstrate: https://codesandbox.io/s/wizardly-estrela-vkf3g2?file=/src/App.js

(Additionally I modified the top-level console.log statement to send the object and string literal to the console as separate arguments, since trying to concatenate them produces incorrect output.)

(As an aside, there's also another error in your browser's console that's easily corrected.)

David
  • 208,112
  • 36
  • 198
  • 279