tibewww
tibewww

Reputation: 603

Fetch Data from json file in React.js

I have a json file call data.json such as ( I use React.js):

[{"id": 1,"title": "Child Bride"}, 
{"id": 2, "title": "Last Time I Committed Suicide, The"}, 
{"id": 3, "title": "Jerry Seinfeld: 'I'm Telling You for the Last Time'"}, 
{"id": 4, "title": "Youth Without Youth"}, 
{"id": 5, "title": "Happy Here and Now"}, 
{"id": 6, "title": "Wedding in Blood (Noces rouges, Les)"}, 
{"id": 7, "title": "Vampire in Venice (Nosferatu a Venezia) (Nosferatu in Venice)"}, 
{"id": 8, "title": "Monty Python's The Meaning of Life"}, 
{"id": 9, "title": "Awakening, The"}, 
{"id": 10, "title": "Trip, The"}]

Im my componentDidMount I have the below:

      fetch('./data/data.json')
.then((response) => response.json())
.then((findresponse)=>{
  console.log(findresponse.title)
  this.setState({
    data:findresponse.title,
  })
})

}

and in my render:

 <ul>

         <li>        {this.state.title}</li>;


    </ul>

I would like to list all the title from my json file,

Otherwise it says that .then((response) => response.json()) is an anonymous function . . .

How to fix this ? I'm a bit confused

many thanks

Upvotes: 2

Views: 31312

Answers (3)

Jared Smith
Jared Smith

Reputation: 21926

Your response isn't an object with a title property, it's an array of objects, all of which have title properties.

this.setState({ data: findresponse });

and then in your render

<ul>
  {this.state.data.map((x, i) => <li key={i}>x.title</li>)}
</ul>

Upvotes: 2

Rilwan
Rilwan

Reputation: 41

You can use async/await. It requires fewer lines of code.

async getData(){
   const res = await fetch('./data/data.json');
   const data = await res.json();
   return this.setState({data});
}

In the componentDidMount() call the function i.e.

componentDidMount(){
   this.getData();
}

Finally, in your render, you map the array of data

render (){
   return {<ul>{this.state.data.map(item => <li>{item.title}</li>)} </ul>
)
}

Upvotes: 4

Boky
Boky

Reputation: 12064

You get the array of objects, thus you need to store then whole object in your state and then from the state read all title properties.

Your fetch should look as follows:

fetch('./data/data.json')
.then((response) => response.json())
.then((findresponse)=> {
  this.setState({
    data:findresponse
  })
})

And then in your render you should have something as follows:

render(){
    return (
      <ul>{this.state.data.map(item => <li>{item.title}</li>)} </ul>
    )
}

That will give you all title properties from data object.

Upvotes: 1

Related Questions