ajax with redux

master
Matt Huntington 9 years ago
parent b623f941bf
commit eee71dc329

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

@ -1,5 +1,6 @@
import React from 'react'; import React from 'react';
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import store from '../store.js';
class CommentsList extends React.Component { class CommentsList extends React.Component {
render(){ render(){
@ -10,6 +11,16 @@ class CommentsList extends React.Component {
</ul> </ul>
} }
componentDidMount(){
fetch('https://stupidcomments.herokuapp.com/comments').then(function(response){
response.json().then(function(data){
let commentsArray = data.map(function(comment){
return comment.body
});
store.dispatch({type:'SET', comments:commentsArray});
});
});
}
} }
const mapStateToProps = function(state){ const mapStateToProps = function(state){

@ -4,6 +4,27 @@ import Comments from './components/comments.jsx';
import { Provider } from 'react-redux'; import { Provider } from 'react-redux';
import store from './store.js'; import store from './store.js';
// fetch('https://stupidcomments.herokuapp.com/comments').then(function(response){
// response.json().then(function(data){
// console.log(data);
// });
// });
// fetch(
// 'https://stupidcomments.herokuapp.com/comments',
// {
// headers: {
// 'Accept': 'application/json',
// 'Content-Type': 'application/json'
// },
// method: "POST",
// body: JSON.stringify({ body:'again from react' })
// }
// ).then(function(response){
// response.json().then(function(data){
// console.log(data);
// });
// });
ReactDOM.render( ReactDOM.render(
<Provider store={store}> <Provider store={store}>
<Comments></Comments> <Comments></Comments>

@ -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