Khant
Khant

Reputation: 1122

Why this redux call is giving me error when refresh the page?

I am new to redux, i am trying to learn how to use redux right now

what i am doing now is i am trying to get data from the redux store

here is the syntax

 class Posts extends Component {
  componentDidMount() {
    this.props.fetchPosts();
  }

  render() {
    console.log(this.props.posts);
    let postItems = this.props.posts.map((post) => (
      <div key={post.id}>
        <h3>{post.title}</h3>
        <p>{post.body}</p>
      </div>
    ));

    return <div>{postItems}</div>;
  }
}

const mapStateToProps = (state) => ({
  // coming from root reducer
  posts: state.posts.items,
});

export default connect(mapStateToProps, { fetchPosts })(Posts);

As you can see in the code the props items are coming from the redux store via mapStatetoProp

The problem is like this

When I change some of the code and save the code the posts are loading fine and were displayed on the page.

But When I refresh the page ctrl r the page will giving me this following error.

TypeError: this.props.posts is undefined

This always happen whenever i tried to refresh the page. I don't understand why this is happening.

here is the post reducer

import { FETCH_POSTS, NEW_POST } from "../actions/types";

const inititalState = {
  // posts that comein from actions
  itemsArray: [],
  // object that we post
  item: {},
};

export default function (state = inititalState, action) {
  switch (action.type) {
    case FETCH_POSTS:
      // console.log('reducer fetching')
      return {
        ...state,
        items: action.payload,
      };
    default:
      return state;
  }
}

Upvotes: 0

Views: 218

Answers (2)

Dario
Dario

Reputation: 6280

In your initialState you don't have any value set for items:

const inititalState = {
  // posts that comein from actions
  itemsArray: [],
  // object that we post
  item: {},
};

items is the property used in your component: posts: state.posts.items and it is only by your reducer when actions FETCH_POSTS is dispatched.

This is why you get the undefined error on page refresh/load, that property (items) just does not exist in your state at startup.

Just define items as an empty array to fix the issue:

const inititalState = {
  // posts that comein from actions
  itemsArray: [],
  // object that we post
  item: {},
  items: []
};

Upvotes: 2

bitsedegitsek
bitsedegitsek

Reputation: 148

Can you try let postItems =this.props.posts && this.props.posts.map((post) => //rest of the code

Upvotes: 1

Related Questions