I'm trying to practice integrating data from separate APIs, but I'm having trouble conceptualizing what the right way is to do so.
Basically, I have two sample APIs I'm fetching from: 1. const API = 'https://hn.algolia.com/api/v1/search?query='; (this.state.hits) const DEFAULT_QUERY = 'redux'; and 2. https://randomuser.me/api/?results=50 (this.state.randomPeople)
I pull them into their own arrays in state via a method called in componentDid Mount.
this.state = {
hits: [],
randomPeople: [],
};
Ideally, I'd like to map over both of them and have data available from each .map result to populate in a single container, something like:
<div>
<img src={random.thumbnailPic}/>
<h3>{random.name.first}</h3>
<h3>{random.name.last}</h3>
<p>{hit.title}</p>
</div>
Just not sure how to approach this the best way. I have only mapped over one data source when populating the results to a container. Should I combine the two arrays and store them together in state? I looked at Lodash, would that work here? Or is there a better way to accomplish this that I just haven't found?
Right now I just have them right on top of another in render() :
{hits.map(hit => (
<div key={hit.objectID}>
<a href={hit.url}>{hit.title}</a>
</div>
))}
{randomPeople.map(rando => (
<div key={random.email}>
<img src={random.picture.medium} />
<h3>Author: {random.name.first} {random.name.last}</h3>
</div>
))}
And here are my methods:
fetchHits = () => {
fetch(API + DEFAULT_QUERY)
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('Something went wrong ... ');
}
})
.then(data => this.setState({ hits: data.hits, isLoading: false }))
.catch(error => this.setState({ error, isLoading: false }));
};
fetchRandomPeople = () => {
fetch('https://randomuser.me/api/?results=50')
.then(results => results.json())
.then(data => this.setState({ randomPeople: data.results }));
};
componentDidMount() {
this.fetchRandomPeople();
this.fetchHits();
this.setState({ isLoading: true });
}
Thanks!