Home > Net >  Why not showing the return value of the function?
Why not showing the return value of the function?

Time:12-14

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 ?

CodePudding user response:

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

CodePudding user response:

You have to await the Axios get method:

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

  • Related