3

Using recompose to load data async as shown below, and in this question, my question is:

-Why does setState(payload) not work within componentDidMount?

The reson I am asking is that it still eludes me, and it is such a pitfall.

const contextTypes = {
    isLoading: PropTypes.bool,
    maler: PropTypes.array,
    selectedMalId: PropTypes.any,
    onSelectMal: PropTypes.func,
    onEditMalText: PropTypes.func,
};

export const addStateHandlers = withStateHandlers({    
    isLoading: true,
    selectedMalId: null,
    maler: [],
}, {
    onDataLoaded: (state, props) => (payload) => {
        debug('onDataLoaded', { state, props, payload });
        return { isLoading: false, maler: payload }
    },
    onSelectMal: (state, props) => (payload) => {
        debug('onSelectMal', { state, props, payload });
        return {
            ...state,
            selectedMal: props.maler.find(mal => mal.id == payload.id),
            selectedMalId: payload.id,
        }
    }
});

export const addAsyncData = lifecycle({
    componentDidMount() {
        getMalerByType(MalTyper.DSB).then(payload => {
            debug('componentDidMount', { payload })                        
            /*
              Do *not* use `setState(payload)` here, because it
              will not be accessible/updated within the handlers
              set by `withStateHandlers`. -Why!!?
            */
            this.props.onDataLoaded(payload); 
        });
    }
});

export const asProvider = withContext(contextTypes, (props) => {
    // Just pass on all props for the defined `contextTypes`as `childContext`
    const childContext = Object.keys(contextTypes).reduce((acc, cur) => ({ ...acc, [cur]: props[cur] }), {});
    debug('asProvider:getChildContext', { props: props, childContext: childContext });
    return childContext;
})

-Applogies in advance if this question is not suited for stackexchange, but I need to ask `cause it still eludes me after hours of research!

Gnimmelf
  • 137
  • 2
  • 9

0 Answers0