0

After a successful POST and GET query, the results of my operation are visible in the console of my React Dev Tools. How should I take those results, preferable create a table and render that table on my web-app itself?

Here is the GET request :

    axios.get('http://localhost:5000/result')
    .then((response) => {
      console.log(response);
        });
    }

The format of results displayed on console is like this : CONSOLE

enter image description here

Let's say I want to create a table by traversing through the results with headers _id and Name. I know I should use the map function. But exactly where and how should I do that in my code?

4
  • Hello, I am doing a project that is similar to this. Did you happen to solve your problem with any of the answers below? I tried them all and was not able to get anything to print on my browser. I'm quite new to react and been at this issue for a few days, so any help would be appreciated. Thanks! Commented Jul 18, 2020 at 10:24
  • @webdesignnoob I did solve the problem by editing my fetch query as follows : I first created a 'data' variable in my state and then I set data equal to the result of my fetch query using ---> fetch('localhost:5000/result', requestOptions) .then(response => response.json() ) .then(json => { console.log(json); this.setState({data:Object.values(json)}); }) .catch(err => { console.log(err) }); -----> Now you can access it using this.state.data and do what you want. Commented Jul 19, 2020 at 2:34
  • Wow! That worked really nicely and makes sense, thank you so much for letting me know how you solved your problem. I've been stuck on this for days! Hope your project is working out for you! Commented Jul 19, 2020 at 3:11
  • @webdesignnoob Happy to help. Commented Jul 19, 2020 at 3:26

4 Answers 4

2

You have a few options. You can make your call in componentDidMount, set the result in a state and then render that state.

componentDidMount() {
   axios.get('http://localhost:5000/result')
    .then((response) => {
      this.setState({
        data: response // maninpulate your response here
      })
        });
    }
}

render() {
   const { data } = this.state;
   return this.renderTable(data) // this should return a table
}
Sign up to request clarification or add additional context in comments.

3 Comments

What's with componentDidMount() ? will I not be able to set the state without it? Reason being that axios request is already being called inside a function operating on he click of a button.
No that was just an example. It wasn't clear that it was being called when clicking a button. @Bharanidhar Reddy solution is good too and better if you have React 16.8. If it's on the onClick, you can still setState as I've shown. Just make sure you put something like this.onClickHandler = this.onClickHandler.bind(this) if you have issues accessing the state in the constructor of the React Component.
Hello, I tried implementing this method and got an error: TypeError: Cannot destructure property 'data' of 'this.state' as it is null. Would you happen to know why I get this error?
1

Assuming you know the concept of 'useState' in react hooks. If not please have an understanding of it.

Long story short, useState is used to store the data in variables.

const [data, setData] = useState();

Instead of console.log(response); you set the response to the variable i.e; setData(response);

In html,

<table>
//some headers, if needed

    //This will iterate your array of objects
    {data.map((eachData) => (
      <tr> <td>{eachData.id}</td>           
       <td>{eachData.name}</td>
       ....
      </tr>
      )
</table>

Please Note: The HTML part works for both class-based and function-based React components where as 'useState' is part of React hooks functionality, works only for function-based components.

Comments

0

I have created a small sample app where I have used react-table for displaying the data as a table. Also In this example I have added promise in order to simulate server fetching data from server. This you can replace with actual server call i.e., axis.get etc.

React-table provides a lot many features that might be helpful. Such as you can provide which columns you wish to display out of all the columns from the data.

If you do not wish to use any library for displaying table, that is also possible only that you have to replace ReactTable with your custom table implementation.

Hope this helps.

4 Comments

I don't know why but I'm unable to "play" with the response variable in any way in my code. Using console.log(response) correctly prints response on the console but setting response as my state data or even printing response as an alert message fails. I have no idea how to extract data from the response variable or why I'm facing this problem.
You can set the response in the state using this.setState(() => ({ data: response })) inside then. So wherever you want to access you can access it through this.state.data. I have done the same in the sample app I have provided in the solution. Or you can also look here
I have looked at your code and I have implemented the exact same thing except that data is still not getting populated with value of the response variable. I don't know where I am going wrong!
One doubt when are you calling the API to get the data? May be if you can share what you are doing only then I can help.
0

Thanks to this page: https://www.skptricks.com/2019/02/can-you-consolelog-in-jsx.html.

You can do console.log in the render function of a class component or in the return statement of a function component. In your case:

function Foo(props){
  data = axios.get('http://localhost:5000/result')
  return(
    <>
      {console.log(data)}
    </>)
}

In my opinion, it's much more straight forward than the other state methods.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.