-4

Here is a function that makes an Axios.get() request:

 const mentorName = (value) => {
    try {
      const res = Axios.get(
        `${BASE_URL}/api/v1/consultations/${value}`
      )
      if (res.status !== 200 || res.data.status !== "success") {
        console.log(res)
        return
      }
    } catch (error) {
      console.log(error)
    }
  }

The below is the output of the console:

Please Click here to see console output

Now, I want to access res.data.data.consultant but When I try to do so. It says that res.data is not valid. This maybe becuase its wrapped in a promise. Please help me be telling How to access it???

EDIT:

Used async/await as suggested:

 const mentorName = async (value) => {
    try {
      const res = await Axios.get(
        `${BASE_URL}/api/v1/consultations/${value}`
      )
      if (res.status !== 200 || res.data.status !== "success") {
        console.log(res)
        return
      }
    } catch (error) {
      console.log(error)
    }
  } 

Async/await gives the following error: Objects are not valid as a React child (found: [object Promise]).

EDIT 2:

mentorName is used inside array.map((row, index)). I am quite sure that nothing is wrong in calling the function.

<TableCell align="left">
   {mentorName(row.consultantID)}
</TableCell>
Paras Bansal
  • 93
  • 1
  • 7
  • To use the axios get like that you'll need to use aysnc/await. Try converting `mentorName` into an async function, and then awaiting `Axios.get`? – evolutionxbox Apr 29 '21 at 10:32
  • No! After writing async and await the program gives the error "Objects are not valid as a React child (found: [object Promise])" – Paras Bansal Apr 29 '21 at 10:36
  • @ParasBansal my suggestion is not an answer. Please edit the question to show what you have tried. – evolutionxbox Apr 29 '21 at 10:37
  • I eaditted the question. Please review it again. – Paras Bansal Apr 29 '21 at 10:39
  • The error given does not related to the code in the example. You are likely dumping an object directly into a react component. – evolutionxbox Apr 29 '21 at 10:41
  • Just removing by two word, i.e., async and await my program works fine and returns the promise. So most probably something is wrong with it and nothing else. My question was how to access data inside a promise and wasn't related to async, await! – Paras Bansal Apr 29 '21 at 10:44
  • can you also add the react code where you want to use `mentorName()` – Punith Mithra Apr 29 '21 at 10:45
  • Removing async and await you're left with a promise. You need the data inside the promise. Therefore you need async/await, or use `then`. _"wasn't related to async, await"_ yes it is. – evolutionxbox Apr 29 '21 at 10:46
  • It's true that react will not accept promises as children. You need to wait until the response is returned from the network. – Punith Mithra Apr 29 '21 at 10:46
  • @PunithMithra sounds like it needs to be ... awaited – evolutionxbox Apr 29 '21 at 10:47
  • `mentorName(row.consultantID)` you can't put this directly inside the render. The data is being fetched asynchronously. Put the result of the function into state and render from the state instead. – evolutionxbox Apr 29 '21 at 10:50
  • Does this answer your question? https://stackoverflow.com/questions/54124947/how-to-use-async-await-in-react-using-the-axios-in-the-api-call – evolutionxbox Apr 29 '21 at 10:53

1 Answers1

0

I have posted a solution to solve your problem. but you can check this post more more detailed understanding of the solution.

 const mentorName = async (value) => {
    try {
      const res = await Axios.get(
        `${BASE_URL}/api/v1/consultations/${value}`
      )
      if (res.status !== 200 || res.data.status !== "success") {
        console.log(res)
        return 'N/A'
      }
      return res.data.name;
    } catch (error) {
      return 'N/A'
    }
  }

Using React Hooks

class App extends Component {
  constructor() {
    super();
    this.state = { row: { consultantID: 123 } };
  }
  componentDidMount() {
      const consultantID = this.state.row;
      mentorName(consultantID).then((name) => {
        this.setState({
            ...this.state,
            row: { ...this.state.row, name }
        });
    });
  }
  render() {
    return (
        <TableCell align="left">
           {row.name}
        </TableCell>
    );
  }
}

React useState() method

docs

   const App = (props) => {
        const [row, setRow] = useState({ consultantID: 123, name: 'N/A' });
    
     mentorName(row.consultantID).then(name =>setRow({
        ...row,
        name,
    }))
    
    return (
       <TableCell align="left">
           {row.name}
        </TableCell>
    )
}
Punith Mithra
  • 608
  • 5
  • 9