MeatballMan
MeatballMan

Reputation: 33

Typescript error "Cannot read property 'data' of undefined" in movie api-app:

Cannot read property 'data' of undefined

I have an issue with my react-typescript movie info app. What I'm trying to do is to display the data I get back from the API but I get stuck on "Cannot read property 'data' of undefined", all components are built but this is a complete road-block.

I've seen a few other examples where people have similar issues but I cannot find any solutions to my problem. I'm not sure where to start looking either. To add to this I have very little experience writing web application, well any applications at all to be honest. Any help will be much appreciated! And if you have any good resources where you can learn about what causes or prevents this type of issue, i'd love to take part of them!

Here's what I get from chrome devtools:

- Uncaught TypeError: Cannot read property 'data' of undefined
- The above error occurred in the <MoviesList> component:
- in MoviesList (created by App)
- in div (created by App)
- in div (created by App)
- in App"

App.tsx

import axios from "axios";
import * as React from "react";
import "./App.css";
import MoviesList from "./Components/MoviesList";
import SearchForm from "./Components/SearchForm";

export default class App extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = { 
      loading: true,
      movies: []
    };
  }

  public componentDidMount() {
    this.performSearch();
  }

  public performSearch = (query = "Cats") => {
    axios
      .get(`http://www.omdbapi.com/?apikey=(API-key)&s=home`)
      .then(response => {
        this.setState({    //<---- Here's where my code breaks in "App"
          loading: false,
          movies: response.data.data
        });
      })
      .catch(error => {
        // tslint:disable-next-line:no-console
        console.log("Error fetching and parsing data", error);
      });
  };

  public render() {
    return (
      <div>
        <div className="main-header">
          <div className="inner">
            <h1 className="main-title">Playpilot Assignment</h1>
            <SearchForm onSearch={this.performSearch} />
          </div>
        </div>
        <div className="main-content">
          {this.state.loading ? (
            <p>Loading...</p>
          ) : (
            <MoviesList data={this.state.movies} />
          )}
        </div>
      </div>
    );
  }
}

MoviesList.tsx

import * as React from "react";
import Movie from "./Movie";

const MoviesList = (props: any) => {
  const results = props.data;
  let movies: any;
  if (results.data) { //<-- Here's where my code breaks in "MoviesList"
    movies = results.map((movie: any) => (
      <Movie url={props.url} key={movie.id} />
   ));
  } else {
    movies = <h1>404: No movies found.</h1>;
  }

  return <ul className="movie-list">{movies}</ul>;
};

export default MoviesList;

Again, thank you!

Upvotes: 2

Views: 5232

Answers (1)

John H
John H

Reputation: 14655

I think this what is causing your problem:

movies: response.data.data

Try changing that to:

movies: response.data

As you've asked for some more general advice, I'd start by learning how to use the DevTools debugger, as it will allow you to become more independent when trying to diagnose problems such as this. Learn how to set breakpoints, and how to step through the code to inspect what's happening. It will save you many hours of grief. Also, don't be afraid to start sprinkling console.log statements throughout your code while you're learning - just remember to remove them afterwards.

Eventually, learning to write automated tests will really help you to have confidence in the code you're writing, but take it one step at a time.

Upvotes: 2

Related Questions