redux works with ajax

master
Matt Huntington 9 years ago
parent 72cd476c1a
commit 0d73d29745

@ -21,7 +21,21 @@ class CommentsForm extends React.Component {
const mapDispatchToProps = function(dispatch){ const mapDispatchToProps = function(dispatch){
return { return {
handleSubmit: function(body){ handleSubmit: function(body){
fetch(
'http://localhost:3000/comments',
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify({ body:body })
}
).then(function(response){
response.json().then(function(data){
dispatch({type:'ADD', comment: { body: body }}); dispatch({type:'ADD', comment: { body: body }});
});
});
} }
} }
} }

@ -28,6 +28,13 @@ import store from './store.js'
// }); // });
// }); // });
fetch('http://localhost:3000/comments').then(function(response){
response.json().then(function(data){
store.dispatch({type:'SET', comments:data});
});
});
ReactDOM.render( ReactDOM.render(
<Provider store={store}> <Provider store={store}>
<App/> <App/>

@ -4,6 +4,8 @@ let comments = function(state = [], action){
switch(action.type){ switch(action.type){
case 'ADD': case 'ADD':
return [...state, action.comment]; return [...state, action.comment];
case 'SET':
return action.comments
default: default:
return state return state
} }

Loading…
Cancel
Save