0

So I'm learning React and got stuck with fetching data from two different APIs and displaying the data into the same table. I can display data from the first API where I get the number and name but when I try to display data from the second API to get the genre, it won't work anymore. I'm not even sure can I do it this way, but hopefully someone can help.

class Stops extends React.Component {
  constructor () {
    super()
    this.state = {
      books: [],
      authors: []
    }
  }
  componentDidMount () {
    fetch('/url1')
      .then((res) => {
        res.json()
          .then(data => this.setState({ books: data }))
      })
    fetch('/url2')
      .then((response) => {
        response.json()
          .then(authorData => this.setState({authors: authorData }))
      })
  }
  Displayauthors (authors) {
    return authors.map((author) => (
      <div key={author.authorId}>
         {author.genre}
      </div>
    ))
  }
  render () {
    const books = this.state.books
    return (
      <div>
        <table>
          <thead>
            <tr>
              <th>number</th>
              <th>name</th>
              <th>Genre</th>
              <th>Download book</th>
            </tr>
          </thead>
          <tbody>
            {
             books.map((book) => (
                <tr key={book.id}>
                  <td>{book.number}</td>
                  <td>{book.name}</td>
                  <td>{this.displayAuthors(this.state.authors)}</td>
                  <td><button type="button">Download</button></td>
               </tr>
             ))
            }
          </tbody>
        </table>
      </div>
    )
  }
}
Ken White
  • 123,280
  • 14
  • 225
  • 444

2 Answers2

0

You could try to fetch the data, but not directly into the state. Instead create something like a "allStuffLoadedNow" Flag in the state.

Workflow

If fetch 1 succeed, it writes the result-data into a local variable (maybe this.prop.fetchResult1) Fetch 2 does the same to this.prop.fetchResult2.

After each success (of both fetch-requests), check if the fetchResult of the other fetch is still done (means you check if this.prop.fetchResult1!==null for example). If it's not null, you set the STATE-Variable allStuffLoadedNow to true, and this cause the re-rendering of your page.

Now you can use your both fetchResults.

Hope that's give you an Idea, how to solve.

suther
  • 12,600
  • 4
  • 62
  • 99
-1

you should put the value in your div like

<div key={author.authorId} value={genre}>
        {author.genre}
     </div> 

and the same for your

<tr key={book.id} value={(number, name)}>

and for the API request you can use axios