user6792790
user6792790

Reputation: 688

How can we update our component on react.js when our prop changes?

I am willing to change my page whenever my prop changes. My prop is important in that it retrieves a specific data that corresponds to the prop.id from an API. Right now, my API request for the prop.id is on the componentWillMount() part, so it only gets runs once. I want to make it change whenver my prop.id changes, and I think I have to use

componentWillReceiveProps(newProps) {    
  console.log('Component WILL RECIEVE PROPS!')
}

shouldComponentUpdate(newProps, newState) {
  return true;
}

to update my page whenever the prop changes, but I am not really sure how this works. I think the componentWillReceiveProps will get run when the prop changes, but I am not sure how to change the shouldComponentUpdate to make the page keep updating when my prop has changed.

Any tips?

EDIT:

A link that directs me to the detail/id page

        return data.map((eachData, index) => {
            return (  <Link to={{ pathname: '/details/' + parseID(eachData.url) }}><PokemonInfo poke={ eachData } key={ index } /></Link> );
        });
    };

goes on to the "/details/" + parseID(eachData.url) which is just an id of the corresponding data. The Next and Prev parts should render the page with id +- 1. It works but the update gets delayed and I have to double click to get the actual prop.

class PokemonDetails extends React.Component {

    constructor() {
        super();


        this.state = {


            pokemon: [],
            imgurl: '',
            abilities: [],
            types: []
        };


    };


    componentWillMount() {
    // Called first time the comp is loaded right before the comp is added to the page
        console.log('Component WILL MOUNT!')
        console.log("passed" , this.props.match.params.id)
        var url = "https://pokeapi.co/api/v2/pokemon/" + this.props.match.params.id; 

        axios.get(url)

        .then((response) => {
            // setState re-renders component
            this.setState({
                pokemon: response.data,
                imgurl: response.data.sprites.front_default,
                abilities: response.data.abilities,
                types: response.data.types,
            })

            console.log(this.state.pokemon)
            console.log('url', this.state.imgurl)
        })

            .catch((error) => {
                console.log(error);
        })
    }

    componentWillReceiveProps(newProps) {    
      console.log('Component WILL RECIEVE PROPS!')
        console.log("passed" , this.props.match.params.id)
        var url = "https://pokeapi.co/api/v2/pokemon/" + this.props.match.params.id; 

        axios.get(url)

        .then((response) => {
            // setState re-renders component
            this.setState({
                pokemon: response.data,
                imgurl: response.data.sprites.front_default,
                abilities: response.data.abilities,
                types: response.data.types,
            })

            console.log(this.state.pokemon)
            console.log('url', this.state.imgurl)
        })

            .catch((error) => {
                console.log(error);
        })
    }

    shouldComponentUpdate(newProps, newState) {
      if(newProps.match.params.id != this.props.match.params.id) return true;
      return false;
    }

    render() {

        let abilities = this.state.abilities.map( (ability, idx) => {
            return(
                <Label key = { idx }>
                    { ability.ability.name }
                </Label>
            )
        });

        let types = this.state.types.map( (type, idx) => {
            return(
                <Label key = { idx }>
                    { type.type.name }
                </Label>
            )
        });

        return (

                <div className="Home">
                    <h1>Gotta catchem all!</h1>
                    <div className="Menu">
                        <Link to="/"><span className="menuSpan">Search</span></Link >
                        <Link to="/gallery"><span className="menuSpan">Gallery</span></Link >

                        </div>              
                <div>
                    <img src= { this.state.imgurl } />
                    <h2>{ this.state.pokemon.name }</h2>

                        <h3>
                            <Link onChange = { this.handleChange } to={{ pathname: '/details/' + (parseInt(this.props.match.params.id) - 1) }}><span>Prev</span></Link>
                            Pokedex #{ this.state.pokemon.id }
                            <Link onChange = { this.handleChange } to={{ pathname: '/details/' + (parseInt(this.props.match.params.id) + 1) }}><span>Next</span></Link>
                        </h3>
                        <h3>
                            Height { this.state.pokemon.height }
                        </h3>
                        <h3>
                            Weight <label>{ this.state.pokemon.weight }</label>
                        </h3>       
                        <h4>Abilities</h4>
                        { abilities }
                        <h4>Type(s)</h4>
                        { types }


                </div>
            </div>

        );
    }
}

Upvotes: 0

Views: 44

Answers (1)

Arun Redhu
Arun Redhu

Reputation: 1579

You can set the condition in the shouldComponentUpdate. When shouldComponentUpdate return a true value then your component's render function will be called. So you can do something like this.

shouldComponentUpdate(newProps, newState) {
  if(newProps.id!==props.id) {
      return true
  }
  return false;
}

Upvotes: 1

Related Questions