Closed fernandojunior closed 7 years ago
I am not sure why you are looking for a full application as an example. This is just one small part of an application. Can you narrow down what you are looking for or what you are having issues with?
Sorry, I expressed myself poorly.
I just want a simple example. How could I apply axios middleware in the following code?
import React from 'react';
import { connect } from 'react-redux';
import axios from 'axios';
const FIND_ALL_COMMENTS = 'FIND_ALL_COMMENTS'
const actionCreators = {
findAll() {
return dispatch => axios.get('/api/comments')(success => {
dispatch({ type: FIND_ALL_COMMENTS, comments: success.data });
})
}
}
function reducer(state = [], action) {
switch (action.type) {
case FIND_ALL_COMMENTS:
return action.comments;
default:
return state;
}
}
const Comment = ({ content }) => (
<div>
<p>{content}</p>
</div>
);
class CommentContainer extends React.Component {
componentDidMount() {
this.findAll();
}
findAll() {
this.props.dispatch(actionCreators.findAll());
}
renderComment({ content }) {
return (<Comment content={content} key={id} />);
}
render() {
return (
<div className="comments">
<h1>Comments</h1>
{ (!this.props.comments || this.props.comments.length === 0)
? <p>No comments yet!</p>
: this.props.comments.map(this.renderComment.bind(this)) }
</div>
);
}
}
export default connect(state => { comments: state.comments })(CommentContainer);
Ah easy!
First, you need to enable the middleware which you can read about here.
Then modify your action creator using the instructions here.
const actionCreators = {
findAll() {
return {
type: 'FIND_ALL_COMMENTS',
payload: {
request:{
url:'/api/comments'
}
}
}
}
}
Last you need to update your reducer to handle the auto generated response action.
function reducer(state = [], action) {
switch (action.type) {
case FIND_ALL_COMMENTS_SUCCESS:
return action.payload.data;
default:
return state;
}
}
Thanks.
Could someone provide a full example App using redux axios middleware?