Reputation: 393
I am trying to create a detailed view for each movie in a list of movies. I have Django as backend and React as frontend.
When I am trying to make a detailed view for each movie I get an error.
Error log:
Failed to compile.
./src/components/movie-list.js
Line 5:26: 'movie' is not defined no-undef
Line 6:28: 'movie' is not defined no-undef
Search for the keywords to learn more about each error.
I have tried to bind but don't fully understand where the problem is.
App.js
import React, { Component } from 'react';
import MovieList from "./components/movie-list";
componentDidMount() {
//fetch data
fetch('http://127.0.0.1:8000/api/movies/', {
method: 'GET',
headers: {
'Authorization': 'Token 8588cb6fcc2ee0bf9915d4c6b720554347d5883f'
}
}).then(resp => resp.json())
.then(res => this.setState({ movies: res }))
.catch(error => console.log(error))
}
movieClicked = movie => {
console.log(movie);
}
render() {
return (
<div className="App" >
<header className="App-header">
<h1>Movie Rater</h1>
<MovieList movies={this.state.movies} movieClicked={this.movieClicked}/>
<MovieDetails movie={this.state.selectedMovie}/>
</header>
</div>
);
}
}
movie-list.js
import React from 'react';
function MovieList(props) {
const movieClicked = movie = evt => {
props.movieClicked(movie);
}
return (
<div>
{props.movies.map(movie => {
return (
<h3 key={movie.id} onClick={movieClicked(movie)}>
{movie.title}
</h3>
)
})}
</div>
)
}
export default MovieList;
I want to make the detailed view work.
Upvotes: 9
Views: 77597
Reputation: 2598
Your code didn't work because your movie variable (inside the fucntion) hold the function refrence (same function) and not the variable you are passing, check the example here (you can test it to understand the issue)
const movieClicked = movie = evt => {
console.log(movie); //shows a function
console.log(evt); // shows the actual value (movie123)
}
movieClicked("movie123"); // work
movie("movie123");// work
Your code is equivalent to
const a = b = 5;
here you get as a result a = 5 and b = 5, in your case movieClicked = movie , both holds the a function as a value. as suggested by Phoenix1355 this code will work
const movieClicked = (movie) => {
props.movieClicked(movie);
}
and also this one will work (doen't make sense in this case but you may encouter this again some day)
const movieClicked = movie = evt => {
props.movieClicked(evt);
}
Upvotes: 0
Reputation: 1652
You're referring to a variable that's outside the scope in the method movieClicked
. Change it to:
const movieClicked = (movie) => {
props.movieClicked(movie);
}
Edit:
As some of the people in the comments are pointing out, the simplified solution would be:
import React from 'react';
function MovieList(props) {
return (
<div>
{props.movies.map(movie => {
return (
<h3 key={movie.id} onClick={() => props.movieClicked(movie)}>
{movie.title}
</h3>
)
})}
</div>
)
}
export default MovieList;
Upvotes: 5