1
votes

Originally had issues with an image loop (it was killing our api calls) and realized we needed to remove componentDidUpdate. Now when inspecting the page with React Dev Tools I can see everything except for the img src updates including the alt tag. If nothing has been rendered to the page then it will render the information correctly but once something is there it changes everything except for the image its self.

class Img extends Component {
constructor(props) {
    super(props)
    this.state = {
        src: ""
    }
}

// componentDidUpdate() {
//     this.getImageId();
// }
componentDidMount() {
    this.getImageId();
}

getImageId() {
    axios.get(`http://localhost:4000/api/images/${this.props.src}`)
        .then(response => {
            console.log(response.data) //this shows only on first request
            this.setState({
                src: response.data
            })
        })
        .catch(err => console.log(err))
}
render() {
    return ( <img src = {
            this.state.src
        }
        alt = {
            this.props.alt
        }
        style = {
            {
                height: "150px",
                width: "200px",
                borderRadius: "10px"
            }
        }
        />
    )
}

}

1
Well in theory, why would you ever need to get the image more than one time? - Chris Ngo
The amount of images isnt the issue its that once a game or a list of games is rendered the first time everything except for the game cover image changes. - Tyler Edge
solution still working? - Chris Ngo

1 Answers

2
votes

As is, your component will only make an API request a single time. And that logic is executed in componentDidMount(). It is a lifecycle event that is executed right after the component is rendered the first time, and never again.

componentDidMount() {
    this.getImageId();
}

The componentDidUpdate() logic you commented out is creating an endless loop. First your initial getImageId() call runs in componentDidMount(). It makes an API request, then it responds with some data and you update component-state with that data.

Any time state or props are updated you trigger componentDidUpdate(). And as currently constructed, your componentDidUpdate() calls getImageId(), which updates state, which then triggers componentDidUpdate(), which then calls getImageId(), which... you get the picture.

You can workaround this. If you only want to make recurring calls to your API when a new src is passed down as a prop from your parent. Do this instead:

componentDidUpdate(prevProps){
   if(this.props.src !== prevProps.src){
      this.getImageId()
   }
}

So now, you only make a new request when there is an updated src provided.