React trying to use .map to populate data from multiple APIs into the same mapped container

Viewed 845

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!

1 Answers

If you're assuming that hits and randompeople are going to be the same length, or if you can somehow align the two arrays, you could add the index parameter to your .map() function:

{randomPeople.map((rando, i) => (
  <div key={rando.email}>
    <img src={rando.thumbnailPic}/>
    <h3>{rando.name.first}</h3>
    <h3>{rando.name.last}</h3>
    <p>{hits[i].title}</p>
  </div>
)}
Related