I have successfully written some code that will go through the redux flow, after the click of a button it will display the information I want on the UI.
I am using the este stack.
This is my button:
const Buttons = ({ requestAsyncData}) => (
<View>
<Button onClick={requestAsyncData}>
<FormattedMessage {...buttonsMessages.add100} />
</Button>
</View>
);
export default connect(state => ({}), { requestAsyncData })(Buttons);
Now here is where I define the action:
export const REQUEST_ASYNC_DATA = 'REQUEST_ASYNC_DATA';
export const requestAsyncData = () => {
return {
type: REQUEST_ASYNC_DATA,
payload: [{
name: "one one!",
id: Math.random()
},{
name: "two two!",
id: Math.random()
}]
}
Here is my reducer:
const State = Record({
map: Map()
}, "names");
const asyncExampleReducer = (state = new State(), action) => {
switch (action.type) {
case actions.REQUEST_ASYNC_DATA: {
const names = action.payload.reduce((names, json) =>
names.set(json.id, new Name(json))
, Map());
return state.update('map', map => map.merge(names));
}
default:
return state;
}
};
export default asyncExampleReducer;
This works exactly as expected on the ui, updating with the correct information, from the action, I get actual payload to do as I please:
payload: [{
name: "one one!",
id: Math.random()
},{
name: "two two!",
id: Math.random()
}]
Now I'm trying to make this payload asynchronous, let's say I will get the information for that object from an ajax api call.
How should I go about it?
I'm not sure if I need to go with thunks or if I should do something like suggested here, I've been trying all sort of recommendations but I'm not sure if my problems are javascript concrete problems or understanding react.
For example I've tried to do an action similar to the one suggested by thunk but it doesn't recognize dispatch and it doesn't seem to delay it either...
function doIncrementAction() {
return {
type: REQUEST_ASYNC_DATA,
payload: [{
name: "trufa!",
id: Math.random()
},{
name: "benja!",
id: Math.random()
}]
}
}
export const requestAsyncData = () => {
return dispatch => {
setTimeout(() => {
// Yay! Can invoke sync or async actions with `dispatch`
dispatch(doIncrementAction());
}, 1000);
};
};
raven.js:290 Uncaught TypeError: Cannot read property 'payload' of undefined
raven.js:290 Uncaught TypeError: dispatch is not a function
How should I go about this? Thanks!!