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

Time:12-21

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:

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?

CodePudding user response:

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>)
}
  • Related