I am trying to get the json data using fetch() method and display it over a webpage using reactjs. As of now the following code prints the data in console but i need the same kind of output over the webpage. How to display it on the page?
import React from 'react';
export default class PersonList extends React.Component {
componentDidMount() {
fetch(`http://localhost:3000/api/testing2`)
.then((response) => response.json())
.then((data) => console.log('This is your data', data));
}
render() {
return<h1>my Component has Mounted, Check the browser 'console' </h1>;
}
}
console output(need this output over the webpage and also need to be define it as a const/let/var/ so that i can access the key-values for further purpose):
This is your data (22) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
In your PersonList class, define a state and update the state upon fetching persons data like this and then render the data,
export default class PersonList extends React.Component {
state = {
persons: [],
}
componentDidMount() {
fetch(`http://localhost:3000/api/testing2`).then((response) => response.json()).then((data) => {
console.log('This is your data', data)
this.setState({ persons: [...data]});
});
}
render() {
return (
<>
<h1>my Component has Mounted, Check the browser 'console' </h1>
{this.state.persons.length && this.state.persons.map((person) => <li>{JSON.stringify(person)}</li>)}
</>
);
}
}