Dennis
Dennis

Reputation: 1975

how to fetch json data and render component (List) according to the response in ReactJS

I want to load book list (book files) from /list endpoint and list them in <ul>. I created a list component and then import it on index.jsx. But it doesn't work. How can I render component with json data fetched from server in body?

list.component.jsx:

import React from 'react'

class List extends React.Component {
  constructor() {
    super()
    this.state = { files: [] }
  }

  componentDidMount() {
    let files = []

    fetch('/books', {
      method: "POST",
      headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
      },
      body: JSON.stringify({ dir: '/' })
    })
      .then(response => response.json())
      .then(data => {
        this.setState({ files: data.books })
      })
  }

  render() {
    return (
      <div>
        <h1>Book List</h1>
        <ul>
          {this.state.files.map(book => {
            return <li key={`book-${book.id}`}>{book.name}</li>
          })}
        </ul>
      </div>
    )
  }
}

export default List

index.jsx:

import List from '../components/list'

document.addEventListener('DOMContentLoaded', () => {
  ReactDOM.render(
    <List/>,
    document.body.appendChild(document.createElement('div')),
  )
})

I see that '/list' fetched in Network tab but no data on the browser.

Errors given:

list.jsx:31 Uncaught TypeError: this.state.files.map is not a function
    at List.render (list.jsx:31)
list.jsx:31 Uncaught (in promise) TypeError: this.state.files.map is not a function
    at List.render (list.jsx:31)

Upvotes: 0

Views: 1082

Answers (2)

Saddam Husen
Saddam Husen

Reputation: 21

Please follow the link https://codesandbox.io/s/2p5p0n4lpn

Just check using ternary operator this.state.files is data available or not. If data is available then render.

{this.state.files ? this.state.files.map(book => { return {book.userId}; }) : null}

Upvotes: 0

Chris Adams
Chris Adams

Reputation: 1454

Have you tried console.log statements directly before the setState command? Might be worth inspecting data and then data.books. Your data might actually be in data and not data.books. data.books might be a string and you may need to JSON.parse it to convert to an array.

Upvotes: 1

Related Questions