0

I am pretty sure the issue I'm running into is that I haven't bound 'this' in the following code, but i'm not sure where to bind it to make it work properly. How would I bind 'this' to make the following code work and not return an error message?

import React from 'react';
import './App.css';
import axios from 'axios';
import Movie from './movie';
import Search from './search';

class App extends React.Component {
  
  state = {
    movies: []
  }
  sendRequest() {

  const options = {
    method: 'GET',
    url: 'https://movie-database-imdb-alternative.p.rapidapi.com/',
    params: {s: 'Avengers Endgame', r: 'json'},
    headers: {
      'x-rapidapi-host': 'movie-database-imdb-alternative.p.rapidapi.com',
      'x-rapidapi-key': 'my_api_key'
    }
  };
  
   axios.request(options).then(response => {
     const movies = response.data.Search;
     this.setState({movies});
    console.log(response.data);
  }).catch(function (error) {
    console.error(error);
  });
};

 render() {
   return (
     <div className="App">
       <header className="App-header">
       { // Use this.state to access movies. 
        this.state.movies && this.state.movies.length ? this.state.movies.map((movie) => {
          return <Movie {...movie}/>
        })
        : null
        }
         <Search handleSendRequest={this.sendRequest}/>
       </header>
     </div>
   );
 }
}

export default App;
Mike Earley
  • 1,075
  • 4
  • 18
  • 39
  • Making `sendRequest` an arrow function would be a quick way to fix this issue as it's losing its context when passed here: `handleSendRequest={this.sendRequest}` – Emile Bergeron Sep 23 '21 at 15:02

0 Answers0