2

I follow the react-redux tutorial and I try to display post. I get the post data from https://jsonplaceholder.typicode.com/posts. it returns the response like this:

enter image description here

import React from 'react';
import { connect } from 'react-redux';
import { fetchPost } from '../actions'

class PostList extends React.Component{
    componentDidMount(){
        this.props.fetchPost();
    }
    renderList(){
        return this.props.post.map(pos => {
            return (
                <div className="item" key={pos.id}>
                    <p>{pos.title}</p>
                </div>
            );
        });
    }
    render(){
        return(<div className="ui relaxed divided list"> {this.renderList()} </div>);
    }
}
const mapStateToProps = (state) =>{
    return { post:state.post}
}
export default connect(mapStateToProps , { fetchPost })(PostList);

this is my action creater

import JsonPlaceHolder from '../apis/JsonPlaceHolder'
export const fetchPost = () => {
    return async (dispatch) => {
        const response = await JsonPlaceHolder.get('/posts');
        dispatch({
            type: 'FETCH_POST',
            payload:response
        });
    }
};

this is my reducer

export default (state=[],action) => {
    switch(action.type){
        case "FETCH_POST":
            return action.payload;
        default:
            return state;
    }
};

this is my ../apis/JsonPlaceHolder file

import axios from 'axios';

export default axios.create({
    baseURL:"https://jsonplaceholder.typicode.com/"
});

but i get the error like this

TypeError: this.props.post.map is not a function

1
  • Please post ../apis/JsonPlaceHolder file Commented Dec 19, 2019 at 8:10

3 Answers 3

1

I think, you should check, whether you have this.props.post or not, before you map it, because request takes some time and during that process you could receive an undefined value from this.props.post.

Plus, if you want to map this.props.post, then you should return as payload not just response, but response.data. Otherwise, you'll get an error, that the object doesn't have a method map.

Sign up to request clarification or add additional context in comments.

Comments

1

You have to extract data from response.

dispatch({
  type: 'FETCH_POST',
  payload:response.data
});

Comments

0

You can also extract the data from response in

const mapStateToProps = (state) =>{
    return { post:state.post.data}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.