Search code examples
reactjsfunctionreturnrender

Why not showing the return value of the function?


function in console.log I can see the correct results

     const getName = (id) => {

        var name = "";
        axios.get( `http://localhost:3001/students/names/${id}`).then((response) => {

          name = response.data[0].Fname + " " + response.data[0].Lname;
          console.log(name);
        })
        .catch((err) => {
          console.log(err);
        });

        return name;
        
      };

render method

 {results.map((value,key)=>(

                                      <tr key={key}>

                                          <td className='columnData'>
                                              { (getName(value.Student_ID))  }
                                          </td> 


Why not showing the return value of the function ?


Solution

  • this is a async function so if you want to get the name just make a state.

    const [name, setName] = useState('')
    const getName = (id) => {
            axios.get( `http://localhost:3001/students/names/${id}`).then((response) => {
    
              setName(response.data[0].Fname + " " + response.data[0].Lname);
              console.log(name);
            })
            .catch((err) => {
              console.log(err);
            });
    
            return name;
            
          };
    

    then you can use the name where ever you want