How can I get a response back from the dispatch action to the component and get the values in the context.
index.jsx :
componentWillMount() {
this.context.store.dispatch(getConfigSettings());
}
Dispatch calls :
export function getConfigSettings(params) {
return (dispatch) => {
dispatch(requestConfig());
admin.getConfig(params,
(response) => {
return dispatch(receivedConfig(response));
},
(error) => {
return dispatch(failedConfig(error));
}
);
};
}
export function getConfig(params, onSuccess, onFailure) {
const url = `${process.env}/admin/data`;
return $.get(url,
(response) => {
onSuccess(response);
}).fail((error) => {
onFailure(error);
});
}
Reducer :
import {
request,
received,
failed
} from '../actions/actions';
const defaultState = Immutable.fromJS({
data: Immutable.fromJS([]),
loading: true,
error: false
});
const reducer = createReducer({
[request]: (state, res) => {
return state.set('loading', true)
.set('error', false)
},
[received]: (state, res) => {
return state.set('data', Immutable.fromJS(res))
.set('loading', false)
.set('error', false);
},
[failed]: (state, res) => {
return state.set('data', Immutable.fromJS({}))
.set('loading', false)
.set('error', true)
}
}, defaultState);
export default reducer;
I have checked the response has the correct value. But how to access that value in the index.jsx I have to display those values in the table.
While you really should just utilize mapStateToProps() to retrieve the data you need from the store, you can return a Promise that resolves the response or rejects the data as follows:
export function getConfigSettings(params) {
return (dispatch) => {
dispatch(requestConfig());
return new Promise((resolve, reject) => {
admin.getConfig(params,
(response) => {
dispatch(receivedConfig(response));
return resolve(response);
// or return resolve(dispatch(receivedConfig(response)));
},
(error) => {
dispatch(failedConfig(error));
return reject(error);
// or return reject(dispatch(failedConfig(error)));
}
);
}
};
}
Then in the component you can access the resolved response or rejected error using then() and catch():
componentWillMount() {
this.context.store.dispatch(getConfigSettings())
.then(response => console.log(response))
.catch(err => console.log(err);
}
Here is an example in action.
I'd really recommend looking into something Promise based for making HTTP calls such as fetch to avoid needing callbacks. redux-thunk works really well with promises.
Hopefully that helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With