How do I know whether or not to update a component?

Asked

Viewed 47 times

1

I’m using the React, React Native and Redux to make an app.

I tried to study a little about the life cycles of a component but ended up getting confused about the various options present when starting it. The problem is this:

When a user is on the screen Feed from my application, it will be able to find a user and eventually tap this and this will open the screen Profile. On this screen, at the event componentDidMount() I do a search using the Redux to obtain the object user. Turns out, I’d like to show you a loading screen before that object gets on props and be "ready". I managed to do that. If I go back to screen Feed and play to see another user, same behavior. The problem is that if I entered the screen Profile to see user X, go back to the Feed and tap user X again, the loading screen will be shown again, which I do not want because, of course, the data is already loaded.

I would like the answer to contain the solution of the problem and also an analysis of whether the form and events I am using are correct for this occasion.

class LocalInside extends Component {

componentDidUpdate(prevProps){
    if(this.props.user != null){
        if(prevProps.user == null){
            this.setState({showUser: true})
        }
        if(prevProps.user != null && prevProps.user != this.props.user){
            this.setState({showUser: true})
        }
    }
}

componentDidMount(){
    const { dispatch } = this.props
    if(this.props.userId != null){
        dispatch(getSingleUser(this.props.userId))
    }
}

state = {
    showUser: false
} 

render(){
    if(this.state.showUser){
        //Aqui mostra o user
    }else{
        //Aqui mostra o carregando.
    }
}
  • Which middleware do you use (Redux Saga, Redux Thunk)? Redux is an object, so inside it you will be "saved" the last loaded data. You can check if the user id is the same as the one in the Redux object. Ai vc uses the middleware to take this and test before calling your API.

  • I am currently using Redux Thunk. How could I do this check that you mentioned?

1 answer

0

You need to save in store that the profile data of the user in question have already been loaded. That is, in the componentDidMount, you check in the store if the hasUserDataLoaded (Linked to userid for example) is false or not. If you haven’t loaded, you render the loading part and already gives a Dispatch of a action to update the store saying that hasUserDataLoaded now is true (This Dispatch is performed within the componendDidMount same). This way, the next time the user accesses the profile, he will not render the loading part again. The point is, in addition to saving the data in the store, you need to save the loading status (or check otherwise, check if the data is empty for example).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.