alphamonkey
alphamonkey

Reputation: 249

(React Native) Retrieving next value in JSON file when button is pressed

Let's say I have a local JSON file (./movies.json) structured as

{ "movies": [ 
    { "title" : "Terminator", "year" :  "1984", "genre" : "Action" },
    { "title" : "Jumanji", "year" : "2017", "genre" : "Adventure"},
    { "title" : "Incredibles 2", "year" : "2017", "genre" : "Animation"}]
}

Whenever a button is clicked, I want to output, for example, a Text Field with Terminator --> Jumanji --> Incredibles 2, in order. I also want to be able to access all three of "title", "movie", "genre" (in separate text fields) in order, when the button is clicked.

This is what I have so far, to get just the titles of the movies in order.It doesn't work, because I don't think I'm pulling from the JSON file correctly.

import jsonData from "./movies.json";

export default class Movies extends React.Component {
  constructor(props) {
  super(props);
      this.state = {
         results:{
         titles: [],
         years: [], 
         genres: []
       }
     }
  };
}
componentDidMount = () => {
  // const data = json.stringify(jsonData)  I think this line is not correct 
  this.setState({ data })
}
render () { 
  titles_list = this.state.results.titles.map((item) => {
  return (
      <View key={item.title}>
        <Text>
          {item.title}
        </Text>
      </View>
    );
 });
return (
  <View>
    {titles_list}
  </View>
);
}
}

I'm not sure how to implement a button so that when it is pressed, the next title/year/genre is shown. Help would be appreciated. Thanks!

Upvotes: 0

Views: 198

Answers (1)

asosnovsky
asosnovsky

Reputation: 2235

Store the index of the array in a state variable. First of all, I will assume that you passed that json into state.movies

So initialize it as follows:

   this.state = {
     movies: [], // where the movies are
     displayIndex: 0 // This will be the index that you show
   }

When you press your button call a function that will call either of the following functions:

moveForward(){
  this.setState({displayIndex: this.state.displayIndex++})
}
moveBack(){
  this.setState({displayIndex: this.state.displayIndex--})
}

Then when you display the fields under your render function grab the object you need as follows:

render(){
   const movieData = this.state.movies[this.state.displayIndex];
   ....//Do the display logic here

Upvotes: 1

Related Questions