Search code examples
node.jsreactjsaxiossetstateuse-effect

React does not show all value of an array returned from axios


This is my backend NodeJS code:

const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
const cors = require('cors');

app.get('/getEmployees', cors(), (req, res) => {
    res.send([
        '00001 | Alice',
        '00002 | Bob',
        '00003 | Charlie',
        '00004 | Dave',
        '00005 | Eve',
        '00006 | Frank',
    ]);
});

app.listen(port, () => {
    console.log(`Server is up on port ${port}`);
});

This is my frontend React code:

import React, { useState, useEffect } from 'react';
import classes from './App.module.css';
import axios from 'axios';

function App() {

    const [employeesList, setEmployeesList] = useState(null);

    useEffect(() => {
        axios.get('http://127.0.0.1:3000/getEmployees').then((response) => {
            console.log(response.data); // Checking value
            let list = [];
            response.data.map((employee) => {
                list.push(<option>{employee}</option>)
                return setEmployeesList(list)
            })
        });
    }, []);

    return (
        <div className={classes.App}>
            Please select employee:
            <select>
                {employeesList}
            </select>
        </div>
    );
};

export default App;

When I run them, I can see a drop down list on the browser but there is only 1 value, which is the first employee, Alice.

enter image description here

As you see, I do console.log in the axios function and it prints multiple employees. I expect to see all employees in the drop down list. Can anyone help me ?


Solution

  • Change your useEffect as below :

      useEffect(() => {
        axios.get('http://127.0.0.1:3000/getEmployees').then((response) => {
          response.data.map((employee, index) => {
            list.push(<option key={index.toString()}>{employee}</option>)
          })
          setEmployeesList(list);
        });
      }, []);
    

    Codesandbox Here