Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeError: Cannot read properties of undefined (reading 'firstname')

I’m new to react and node (express)
I’m trying to get some date from a database (‘firstName’ and ‘lastName’),concatenate and display them in a select tag.

There is what I do:

The request I sent to the database in my node file:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

app.get("/employeesName", (req, res) => {
  db.query("SELECT firstname , lastname FROM employees", (err, result) => {
    if (err) {
      console.log(err);
    } else {
      res.send(result);
    }
  });
});

The get request in react:

const [employeeList, setEmployeeList] = useState([]);
  useEffect(() => {
    const  getEmployeesNames = () => {
      Axios.get("http://localhost:3001/employeesName").then((response) => {
        setEmployeeList(response.data);
      });
      }; 
          getEmployeesNames();

  },[])

I tried something like that to diplsay my data in the select tag:

 <select>
        <option value="">{employeeList[0].firstname+" "+employeeList[0].lastname}</option>
        <option value="">{employeeList[1].firstname+" "+employeeList[1].lastname}</option>         
 </select>

When I do that in vs code It works,but just when I refresh my page In the browser I get that error (Cannot read properties of undefined),I think that employeeList is empty on first render. Which Is reasonable as my initial state is an empty array (useState([]);),I tried to initialize
my useState with something like that useState([{firstname: 'test', lastname: 'test2'}]); but still get the error

What should be done to avoid this error?

>Solution :

useState([{firstname: 'test', lastname: 'test2'}])

This array has one element so employeeList[1] will be falsy


You can just conditionally render the select:

{
    employeeList.length > 0 && (
        <select>
            {
                employeeList.map((emp, index) => <option key={index} value={index}>{emp.firstname + " " + emp.lastname}</option>)
            }
        </select>)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading