Reputation: 21
Playing around with fetch data in an async action in redux and using a reducer. Just need some help fetching the data into the reducer. Below is what i have so far.
actions.js
function receiveData(loadData) {
return {
type: 'RECEIVE_POSTS',
loadData
};
}
function schemaData(loadData) {
return dispatch => {
return fetch(`www.fetchurlhere`)
.then(response => response.json())
.then(json => dispatch(schemaData(loadData, response.data)));
};
}
reducer.js
export default function schemaData(prevState = {}, action) {
if (action.type === 'RECEIVE_POSTS') {
return action.receiveData;
} else {
return prevState;
}
}
I can see the reducer 'schemaData' in the store but its empty. Never requested a fetch in an action before. I have had a look at the redux example and tried to modify for mine. But its empty so something is missing.
Upvotes: 0
Views: 306
Reputation: 10179
Try this:
actions.js
function receiveData(loadData) {
return {
type: 'RECEIVE_POSTS',
receiveData: loadData
};
}
function schemaData() {
return dispatch => {
return fetch(`www.fetchurlhere`)
.then(response => response.json())
.then(json => dispatch(receiveData(json)));
};
}
reducer.js
export default function schemaData(prevState = {}, action) {
if (action.type === 'RECEIVE_POSTS') {
return action.receiveData;
} else {
return prevState;
}
}
This is a small demo: https://codesandbox.io/s/3vmn3lvp76
Upvotes: 2