Why is this array undefined in React?

Asked
Active3 hr before
Viewed126 times

8 Answers

undefinedarrayreact
90%

You are setting state too soon. In your callback function you need to setState after assigning to list_files and list_folders since the callback is executed after the constructor has finished. Try this:,Then move your console.logs to your render function to see the state being updated. Once on initial construction and once again after setState.,Find centralized, trusted content and collaborate around the technologies you use most.

You are setting state too soon. In your callback function you need to setState after assigning to list_files and list_folders since the callback is executed after the constructor has finished. Try this:

for (var i = 0; i < response.data.length; i++) {
   if (response.data[i]["isFile"] == true) {
      list_files.push(response.data[i]);
   } else {
      list_folders.push(response.data[i]);
   }
}
// setState here:
this.setState = {
   files: list_files,
   folders: list_folders
};
88%

getting an error, Uncaught TypeError: Cannot set property ‘undefined’ of undefined,Which is identical to the method that preceeds it as far as I can tell in terms of it’s syntax, values passed in, etc. The error is in this line specifically:,the error comes in this method:

import React, {
   Component
} from 'react'
import './World.css'

let rooms = []
let items = []

class World extends Component {
   constructor(props) {
         super(props)

         let startrows = 40
         let startcols = 60

         let arr = Array(startrows).fill().map(() => Array(startcols).fill(0))
         this.generateRooms(arr, startrows, startcols, rooms, items)

         console.log("Rooms: ", rooms)
         console.log("Items: ", items)
         //this.drawRooms(arr, rooms)
         //this.drawItems(arr, items)
load more v
72%

The first sends me undefined, the second sends me an array with all the data.,What I have checked if that if I do console.log(this.state.articles) I get two responses. The first sends me undefined, the second sends me an array with all the data.,I´m trying to work with an array, set on the status of the component after using axio to get the data from an url.

I´m trying to work with an array, set on the status of the component after using axio to get the data from an url.

import React, { Component } from 'react';
import axios from 'axios';

class Articulo extends Component {

  constructor(props) {
    super(props);
    this.state = {
      url : 'http://aldeasinfantiles-wp.lin3sdev.com/wp-json/wp/v2/posts?slug=' + this.props.match.params.slug
    }
  }

  state = {
    articles: [],
  };

  componentDidMount() {
    axios.get(this.state.url).then(res => {
      this.setState({ articles: res.data});
    });
  };

  render() {
    return (<h2>Este es el slug del artículo: {console.log(this.state.articles)}</h2>)
  }

}

export default Articulo;

this.state.articles is just the full array, but I don’t know how to access to the data. I have also tried this:

render() {
    return(<div>{this.state.articles.map( article => <article><h1>{article.title}</h1></article>) }</div>)
}
load more v
65%

Pretag
 Pretag team - issue, fix, solve, resolve
75%

This error usually means you’re trying to use .map on an array, but that array isn’t defined yet.,That’s often because the array is a piece of undefined state or an undefined prop.,There are a ton of potential causes for an error like this, though.

   6 | return (   7 |   <div className="App">   8 |     <h1>List of Items</h1>>  9 |     {items.map((item) => (     |           ^  10 |       <div key={item.id}>  11 |         {item.name}  12 |       </div>
load more v
40%

The variable you are trying to map over is undefined. It will probably eventually be an array, but due to the asynchronous nature of React, you are experiencing at least one render when the variable is undefined.,This is one of the more common errors you will run into when starting out with React:,And now we have a pretty safe way of handling our async operation without getting the dreaded “cannot read property ‘map’ of undefined” error!

Cannot read property 'map' of undefined
load more v
22%

https://www.codecademy.com/paths/build-web-apps-with-react/tracks/react-capstone/modules/jammming-capstone/projects/jammming-prj,I have a state in App.js that contains some songs… I pass it to another component SearchResults which passes it to Track component… This is where the problem is. I can type ‘console.log(this.props.searchResults)’ and i can see the array of songs on the console.,It says ‘TypeError: this.props.searchResults is undefined’

But if i put it in the return statement like this:

import React from 'react';
import Track from '../Track/Track';
import './TrackList.css';

class TrackList extends React.Component {
  render() {
    console.log(this.props.searchResults);
    return (
      <div className='TrackList'>
        {this.props.searchResults.map(data => (
          <Track />
        ))}
      </div>
    );
  }
}

export default TrackList;

load more v
60%

Which means that in the first render of our component, react will “see” our items as an empty array, so instead of running undefined.map(...) like before, it will run [].map(...).,React evaluate our return statement, when it hits the items.map(...) line its actually running undefined.map(...) which is obviously an error in JavaScript.,React will run all effects after the render is committed to the screen, which means we can’t avoid a first render without our data.

// Just a data fetching function
const fetchURL = "https://jsonplaceholder.typicode.com/todos/";
const getItems = () => fetch(fetchURL).then(res => res.json());

function App() {
  const [items, setItems] = useState();

  useEffect(() => {
    getItems().then(data => setItems(data));
  }, []);

  return (
    <div>
      {items.map(item => (
        <div key={item.id}>{item.title}</div>
      ))}
    </div>
  );
}
load more v

Other "undefined-array" queries related to "Why is this array undefined in React?"