I have a problem rendering the list of all the post with React, I want to render a function with a mapping of posts
but it tells me that the one that is undefined, that is due. I used mapStateToProps
to call the array todos
my component ListPost
import React from 'react';
import {connect } from 'react-redux';
import {cargaPost} from '../acciones/index';
import {Link} from 'react-router-dom';
class ListaPost extends React.Component {
componentWillMount() {
this.props.fetchPost();
}
renderPost () {
return this.props.posts.map( post => {
return(<li className="list-group-item" key={post.id}>
<span className="text-right">{post.title}</span>
</li>)
})
}
render() {
// const { posts } = this.props;
// if (!posts) {
// return <div>Loading...</div>
// }
return (
<div>
<div className="text-right">
<Link
to="/posts/new"
>
<button
type="button"
className="btn btn-info">
Nuevo Post
</button>
</Link>
</div>
<ul className="list-group">
{this.renderPost()}
</ul>
</div>
)
}
}
const mapStateToProps = (state) => {
return { posts: state.posts.todos }
}
export default connect(mapStateToProps, {fetchPost: cargaPost})(ListaPost);
my actions
import axios from 'axios';
export const FETCH_POST = 'FETCH_POST';
export const CREAR_POST = 'CREAR_POST';
const URL = 'http://reduxblog.herokuapp.com/api';
const API_KEY = '1234557';
// ListaPost
export function cargaPost () {
const solicitud = axios.get(URL)
.then( res => { console.log(res) })
return {
type: FETCH_POST,
payload: solicitud
}
}
and the reducer
import {FETCH_POST} from '../acciones/index';
const estadoInicial = { todos:[], unPost: null }
// PostReducer
export default function(state=estadoInicial, accion) {
switch(accion.type) {
case FETCH_POST:
return {...state, todos: accion.payload.data }
default:
return state;
}
}