How to re-render a React Component Upon re-direct

Viewed 2131

I am creating a clone of SoundCloud, and when I delete a song from the song page, I want to re-direct to the song index component (the /discover page).

I am able to successfully re-direct there upon deletion, but the index page appears empty until I refresh, whereupon the songs are fetched. I've tried using a ComponentDidUpdate on the index page to fetchSongs again when the history.location is different, but haven't had success.

//Song Delete Component
handleDelete() {
    this.props.removeSong(this.props.songId)
    this.props.history.push("/discover");
}

//Song Index Component
componentDidUpdate(prevProps) { 
    if (this.props.history.location.pathname !== 
        prevProps.location.pathname) {
        this.props.fetchSongs(); 
    }
}
1 Answers

When your redirect to a new component/route, that component gets re-mounted to the screen. You should use componentDidMount() instead;

Discover Component:

componentDidMount() { 
     this.props.fetchSongs(); 
}

Edit ---

Just learned that your second page is actually a modal and that you execute your action-creatorand redirect in there. In that case, the Discover component may have not actually unmount from the screen, hence why componentDidMount() does not execute. But componentDidUpdate() should still work, let's refactor it a bit

So in Discover Component, try something like:

componentDidUpdate(prevProps){
    if(this.props.songsOrNameOfReducerKey !== prevProps.songsOrNameOfReducerKey){
        this.props.fetchSongs()
    }
}

this.props.songsOrNameOfReducerKey just refers to the redux-state that holds the updated list of songs - available as a prop in your component. We compare the updated list to our previous list, and if there is a difference, we execute your action-creator. Make sure you connected redux to your component via mapStateToProps() to get a hold of this state-value. Replace songsOrNameOfReducerKey with the key that you defined.

When you delete the song from your list, it should give the Discover component, new props, thus triggering componentDidUpdate()

Related