How to access state values by index in React

react setstate update array element
react setstate array
react update object in array
react state array length
react array of objects
how can you access the state of a component from inside of a member function
react get state value
react access state from outside

I'm struggling to access values inside a state in React using axios and my code is as follows:

import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';

class App extends React.Component {
  state = {
    moviedata:null
  }

  getMovies(){
    axios.get("http://127.0.0.1:8000/api/v1/movies/")
      .then(moviedata => {
        this.setState({
          moviedata: moviedata.data    
        });
      })
      .then(x => { console.log(this.state.moviedata)});
  }

  componentDidMount(){
    this.getMovies();
  }

  render () {
    return <h1>Movie Examples include </h1>
  }
}

ReactDOM.render(<App />, document.getElementById('react-app'));

The console.log looks like this:

0: {title: "Terminator 2: Judgement Day", plot: "Rise of the machines.", year: 1991}
1: {title: "The Italian Job", plot: "A comic hinging on a traffic jam", year: 1969}

How can I include the title of the first entry, i.e. 'Terminator 2: Judgement Day', inside the h1 tag, after the word 'include'?

I tried:

render () {
  return <h1>Movie Examples include {this.state.moviedata[0].title}</h1>
}

and got an error TypeError: Cannot read property '0' of null

moviedata in your component state is initially null, so trying to access [0] from that will give rise to your error.

You could e.g. return early from the render method until moviedata has been set.

Example

class App extends React.Component {
  // ...

  render() {
    const { moviedata } = this.state;

    if (moviedata === null) {
      return null;
    }
    return <h1>Movie Examples include {moviedata[0].title}</h1>;
  }
}

React, React - accessing specific index of array in state with a variable the screen ( which reliably runs all the code again, so new random value,� In React, both this.props and this.state represent the rendered values, i.e. what’s currently on the screen. Calls to setState are asynchronous - don’t rely on this.state to reflect the new value immediately after calling setState .

You have to account for the fact that the Axios request is asynchronous, so the component may render before the data are loaded. For example:

render () {
  const data = this.state.moviedata;
  return <h1>Movie Examples include {data ? data[0].title : ""}</h1>
}

How to Work with and Manipulate State in React, Let's get started with accessing state in React components. The source code / clock - index.html /jsx - script.jsx - clock.jsx /js - script.js - clock.js - react-15.0.2.js - react-dom-15.0.2.js The value of this.state must be an object. Use React Context API. Instead of props, you can also use the Contexts API.. Using Redux for Accessing and Updating Parent State from Child Component. If your application is more complex than this simple example, you can use a state management library like Redux and connect() both the App and ContactForm components to the contacts in Redux store.

First, you have to "know" that the component is in a "loading" state. Without that, your state data is undefined (Still loading)

Here's how to do it:

class App extends React.Component {
  state = {
    moviedata:null,
    isLoading: true
  }

  getMovies(){
    axios.get("http://127.0.0.1:8000/api/v1/movies/")
      .then(moviedata => {
        this.setState({
          moviedata: moviedata.data,
          isLoading: false
        });
      })
      .then(x => { console.log(this.state.moviedata)});
  }

  componentDidMount(){
    this.getMovies();
  }

  render () {
    if (this.state.isLoading) {
      return <h1>Please wait...</h1>
    }

    // show only the first movie
    return <h1>Movie #1 {this.state.moviedata[0].title}</h1>;

    // show all the movies
    return (
      <>
        {this.state.moviedata.map((m, idx) => <h1 key={idx}>Movie: {m.title}</h1>}
      </>);
  }
}

How to manage React State with Arrays, Learn how to manipulate arrays in React state by using JavaScript array of a React component and afterward used by accessing it via the React spread all key value pairs of the initial state object to the initial state of the component. In this case, you take the index of the item in the array to identify it� and want to create this.state.books.length - as a number - Book components each have props from the books array of the Library component's state. We have to deal with the two components. First with the parent, we have to create the Book component this.state.books.length - as a number - times, and pass our diffrent values to them Like this: Full

Lists and Keys – React, We don't recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state. function ListItem(props) { const value = props.value; return ( // Wrong! React State: Update item in array. In this part of the walkthrough, we will go through two cases to update items in an array: How to update the entire array in React state? How to update a specific item in array in React state? In both cases, the array map method is our friend. Whereas the array concat is used to add an item to an array, the

Reconciliation – React, On the next state or props update, that render() function will return a different tree of Reorders can also cause issues with component state when indexes are� I'm trying to figure out how to notify another component about a state change. Let's say I have 3 components - App.jsx,Header.jsx,and SidebarPush.jsx and all I'm simply trying to do is toggle a class

DOM Elements – React, Style keys are camelCased in order to be consistent with accessing the properties If you want to use units other than “px”, specify the value as a string with the� This is a way to “preserve” some values between the function calls — useState is a new way to use the exact same capabilities that this.state provides in a class. Normally, variables “disappear” when the function exits but state variables are preserved by React.

Comments
  • Thanks this worked! I'm still a beginner so really happy of the simplicity in your answer:)
  • So does the render function keep looping until moviedata is set before continuing to the return statement ?
  • @West Great! You're welcome. A component is re-rendered when the state or props changes, so the render method will be run once before your data is loaded, and then once again when you use setState in the axios callback.
  • Understood! Cheers mate
  • I tried this and nothing got displayed after 'include'
  • Thanks will look into this. I'm still new to React so not sure at the moment how to properly include your last return statement in my case
  • In my example I'm showing all the movies. I'll add an example to show only the first movie.
  • Okay great I get your example now. Thanks