We would now like to retrieve data from a remote server and use it to populate a <ContactList>
.
We'll separate concerns: we'll split out the fetching of data from the rendering of that same data.
To do this, we'll create a <ContactListContainer>
component. This is just responsible for data fetching. Once the data has arrived, it will be rendered using our <ContactList>
.
Note the differences between the two:
- The
<ContactList>
is a presentational component. Given props, it just renders the data provided, so it's pretty simple. - The
<ContactListContainer>
is a "container" component. It doesn' do much rendering, but has more behavior. In particular, it fetches the data and then renders a<ContactList>
, passing all the data to it in a prop.
We need a server and some data.
-
Place your contacts.json in the
public/
folder in yourcreate-react-app
project. -
Now check that you can access it via http://localhost:3000/contacts.json.
Create the <ContactListContainer>
class. It'll need to fetch the data, and render a <ContactList>
.
To do the fetching, use either jQuery, the Fetch API (example below), or a mechanism of your choice.
I suggest using the lifecycle method componentDidMount()
to fetch the data.
Here's an example using Fetch:
fetch('http://localhost:8060/api/contacts')
.then(response => response.json())
.then(json => console.log(json))
.catch(ex => {
console.log('Err:', ex);
});
And here's an example using jQuery:
retrieveEvent(siteId, location, type) {
const anHourAgo = moment.utc().add(-1, 'hours').format();
$.ajax(`/api/event/history?siteId=${siteId}&location=${location}&type=${type}&since=${anHourAgo}`, {
success: (datasets) => {
this.setState({event: datasets[0] });
},
error: (xhr, err) => {
this.setState({error: {
message: 'Event not found',
detail: xhr.responseText,
code: xhr.status,
error: err,
}});
},
cache: false,
});
}