0

My ImageGallery component is not updating itself when my URL changes.

For example, when I click an item it routes me from '/movies/12345' to '/movies/9999', but the component itself is not updating to show the images associated with '/movies/9999'. Instead it shows the images associated with '/movies/12345'.

Parent Component:

class Parent extends Component { 
  componentDidMount() {
    this.props.fetchImages(this.props.match.params.id);
  }

 render(){
   ..
     <ImageGallery />
   ..
  }
}

export default connect(mapStateToProps, { fetchImages })(Parent);

ImageGallery Component:

class ImageGallery extends Component {
    render(){
      return this.props.images.map(img => {
           <img src={img.image_path}
      })
}
}

And then I tried wrapping my connect function with withRouter and used componentWillReceiveProps. But this doesn't work it complains

Cannot read property id of Undefined

class Parent extends Component { 
  componentDidMount() {
    this.props.fetchImages(this.props.match.params.id);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.match.params.id !== this.props.match.params.id) {
      this.props.fetchImages(nextProps.params.id);
    }
  }

 render(){
   ..
     <ImageGallery />
   ..
  }
}

export default withRouter(
  connect(mapStateToProps, { fetchImages })(Parent)
);

App.js

  <div>
    <NavBar />
    <Router history={history}>
      <Route exact path='/' component={Landing} />
      <Route exact path='/movies/:id' component={Parent} />
    </Router>
  </div>

How do I get the ImageGallery to display the correct images? Thanks.

2 Answers 2

1

Please add render to Route

When you change /movies/12345 to /movies/9999 component will not render so for that we are adding key to component

App.js

<div>
  <NavBar />
  <Router history={history}>
    <Route exact path='/' component={Landing} />
    <Route
      exact
      path='/movies/:id'
      render={({ match }) => <Parent key={match.params.id || ''} />} // Add render 
    />
  </Router>
</div>
Sign up to request clarification or add additional context in comments.

1 Comment

For more info on this solution: medium.com/@migcoder/…
0

Check if the store updates when you fetch new images in componentWillReceiveProps. Otherwise it seems fine. There might be something wrong with the reducer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.