Pablo Estrada
Pablo Estrada

Reputation: 3462

Dipatching an action before mapStateToProps in React Redux

I'm working on a userProfile container component in react which displays some data after fething it from a server.

This is the component:

import React from 'react';
import {connect} from 'react-redux';
import PersonalInformationView from './PersonalInformationView';
import * as selectors from '../../../reducers';

    class PersonalInformationViewContainer extends React.Component{
        constructor(props, context){
            super(props, context);

        }

        render(){
            return (
                    <PersonalInformationView userProfile={this.props.userProfile}/>
            );
        }

    }


    const mapStateToProps = (state, ownProps) => {
        return {
            user: selectors.getUser(state),
            userProfile: selectors.getUserProfile(state)
        };
    };

    const mapDispatchToProps = () =>{
        return {

        };
    };
    export default connect(mapStateToProps, mapDispatchToProps)(PersonalInformationViewContainer);

The problem Im having is that I need to dipatch the action FETCH_USER_PROFILE_STARTED that calls a saga and brings the data. This needs to be done before calling the selector getUserProfile because Im getting an undefined as a result with the above code.

What is the best way to ensure I have finished fetching the data so the props.userProfile is not undefined in my component?

Upvotes: 1

Views: 503

Answers (1)

Jalil
Jalil

Reputation: 3168

You can simply add

if (!this.props.userProfile)
  return null;

at the beginning of your render method so that the component renders empty.

Or render a loading text or animation instead of null while waiting for the fetch.

Or don't render the component at all by putting the test higher in component hierarchy...

Technically, you could avoid calling the getUserProfile selector before the fetch starts but this would end up in an unnecessary complicated, ugly, unmaintainable and unreadable code... Why would you do that?

You actually want to call the selector and you want it to return undefined which is the simple truth...

Upvotes: 3

Related Questions