Search code examples
javascriptreactjsfetch

Undefined value. Trying to set ID with fetch


I can access the data directly via the API, and I can make the onClick display data so I know that it triggers. The fetch fails because the Id is undefined however I cannot work out why the id is never defined.

Code:

import React from 'react';
import Film from './Film.js';


class Actor extends React.Component {

 state = {
    display:false, 
    data:[],
  }

 loadFilmDetails = () => {
   const url = "http://localhost/c/api/films?actor_id=" + this.props.details.actor_id
   fetch(url)
     .then( (response) => response.json() )
     .then( (data) => {
       this.setState({data:data.data})
     })
      .catch ((err) => {
        console.log("something went wrong ", err)
     }
   );
 }

 handleActorClick = (e) => {
   this.setState({display:!this.state.display})
   this.loadFilmDetails()
 }

 render() {

   let films = ""
   if (this.state.display) {
     films = this.state.data.map( (details, i) => (<Film key={i} details={details} />) )
   }

   return (
     <div>
       <h2 onClick={this.handleActorClick}>{this.props.details.first_name} {this.props.details.last_name}</h2>
       {films}
     </div>
   );
 }
}

export default Actor;

If I do console.log(this.prop.details) I get an object with some data, but no actor_id.

How do I make it so that const url = "http://localhost/a/api/films?actor_id=" + this.props.details.actor_id actually sets a value to actor_id (which is currently always undefined).


Solution

  • There can be two issues :

    1. Either you are not passing the props details.actor_id from the parent to Actor component correctly.

    2. Or the Actor Component has rendered before the props were available to it that's why you are getting the undefined.

    And if it is the second case. Then you must first use an additional check on before making an fetch call.

    Try this code change, once or share your codesandbox link (for us to see what is going on)

     handleActorClick = (e) => {
       this.setState({display:!this.state.display});
       this.props.details.actor_id && this.loadFilmDetails();
     }