0

so I have an Action, which fetches some data from rest. In a component, i need this data from the fetch, which is set in store. I use this data then like someFunc(this.props.data) in componentDidMount(). Afterwards i give the return value of someFunc an another Action, which does something with this data and also sets it in store.

My only idea is, to give someFunc to the Action as a callback and call this right after the first data is fetched. So i have 2 dispatched in one action.

I hope you guys understand what i mean. Is there a better way to do this?

Edit

In Component1 i dispatch an Action, which loads data i need to the store. In Component2 i dispatch another Action, which gets his value from someFunc function. But someFunc gets the data from the first Action, so the data is undefined when i call someFunc, because the data isn't set in the store yet.

More clear yet?

Component1

componentDidMount(){
        this.props.dataLoadAction()   //action for the fetch i told
}

const mapDispatchToProps = (dispatch) => {

    return {
        dataLoadAction: () => {
            dispatch(dataLoadAction())
        }
    }
};

export default connect(null, mapDispatchToProps)(Component1);

Component2

componentDidMount(){
        this.props.changeDataAction(this.someFunc(this.props.data))
}

render(){
        return (
            <div>
                {this.props.otherData}
            </div>
        )
    }

const mapStateToProps = (state) => {

    return {
        otherData: state.someReducer.otherData,
        data: state.someReducer.data,
    }
};

const mapDispatchToProps = (dispatch) => {

    return {
        changeDataAction: (changedData) => {
            dispatch(changeDataAction(changedData))
        }
    }
};

export default connect(mapStateToProps, mapDispatchToProps)(Component2);

Actions

export function dataLoadAction(){
    return dispatch => {

    HttpRequest.getJson("some url", json => {

            dispatch(
                {
                    type: 'DATA_LOADED',
                    payload: {
                        data: json
                    }
                }
            )
        });
    });
};

}

export function changeDataAction(changedData){
    return dispatch => {

        dispatch(
            {
                type: 'LOAD_CHANGEDDATA',
                payload: mappedVis
            }
        )

    };
}
Muco
  • 53
  • 11

0 Answers0