Skip to content Skip to sidebar Skip to footer

Redux-thunk: Pause Component Execution Until Action Creator Completes

I've been struggling with this problem for several weeks now. I'm finally throwing in the towel and asking for help on this because I'm clearly not doing something right. I have a

Solution 1:

  1. your action(fetch) in componentWillMount is async ,component will not wait.
  2. Usually when you fetch some data , you want to know about statuses of fetching process. like "isfetching" in order to showing loader, success and failure in order to showing error.
  3. You can use these statuses to not load/mount/launch component, Until Action Creator Completes.

Thus, you should organize your redux parts somthing like that:

state

activePlayer:{
    data:data,
    isFetching: true/false,
    error:""
    }

action

exportconstfetchActivePlayer = slug => dispatch =>{
    dispatch({
        type: 'FETCH_ACTIVE_PLAYER_REQUEST',
        isFetching:true,
        error:null
    });

    return axios.get(`${ROOT_URL}/players/${slug}`)
    .then(response => {
        dispatch({
            type: 'FETCH_ACTIVE_PLAYER_SUCCESS',
            isFetching:false,
            payload: response
        });
    })
    .catch(err => {
        dispatch({
            type: 'FETCH_ACTIVE_PLAYER_FAILURE',
            isFetching:false,
            error:err
        });
        console.error("Failure: ", err);
    });

};

reducer

const initialState = {data:null,isFetching: false,error:null};
export const actionPlayer = (state = initialState, action)=>{
    switch (action.type) {
        case'FETCH_ACTIVE_PLAYER_REQUEST':
        case'FETCH_ACTIVE_PLAYER_FAILURE':
        return { ...state, isFetching: action.isFetching, error: action.error };

        case'FETCH_ACTIVE_PLAYER_SUCCESS':
        return { ...state, data: action.payload, isFetching: action.isFetching,
                 error: null };
        default:return state;

    }
};

then your component might look like this (hardcode)

classPlayerDetailContainerextendsComponent{
    componentWillMount() {
        this.props.fetchActivePlayer(this.props.params.player_slug)
    }
    render() {
        if (this.props.isFetching) {
            return <Spinner text="Loading..." style="fa fa-spinner fa-spin" />

        }elseif (this.props.error) {
            return <div>ERROR {this.props.error}</div>
        }else {
            return <PlayerDetails  player={ this.props.data }  />
        }
    }
}
const mapStateToProps = state =>({
        isFetching: state.activePlayer.isFetching,
        data: state.activePlayer.data,
        error: state.activePlayer.error,
})

I don't know how your app looks like. Target of this example is to illustrate approach.

Post a Comment for "Redux-thunk: Pause Component Execution Until Action Creator Completes"