useSelector property returns undefined

I'm trying to fetch 'all posts' using Redux. I should be getting an empty array but instead, I'm getting undefined. Here's my reducer:

export default (posts = [], action) => {
  switch ((action.type)) {
    case "FETCH_ALL":
      return action.payload;
    case "CREATE":
      return posts;

    default:
      return posts;
  }
}; 

Action


export const getPosts = () => async (dispatch) => {
  try {
    const { data } = await api.fetchPosts();
    dispatch({ type: "FETCH_ALL", payload: data });
  } catch (error) {
    console.log(error.message)
  }
};

Posts.js component

import { useSelector } from "react-redux";
import Post from "./Post/Post";
import useStyles from "./styles";

const Posts = () => {
  const posts = useSelector((state)=>state.posts)
  console.log(posts)
  const classes = useStyles();
  return (
    <>
      <h1>Posts</h1>
      <Post />
    </>
  );
};

export default Posts;

Upvotes: 1

Views: 153

Answers (3)

Ken Ha
Ken Ha

Reputation: 127

  1. Firstly, switch ((action.type)) should be switch (action.type)
  2. Then, you should check the data from api whether it's returned correctly or not
  3. Finally, check your redux state object and your selector of posts

Upvotes: 0

According to your reducer, your entire state is a posts array instead of a state object like { posts: [ ] }. So in your selector, you can simply return the state as it is in the Posts component.

 const posts = useSelector((state)=>state);

Upvotes: 3

Arrow
Arrow

Reputation: 542

I believe that you need to change a line in your reducer file. You need to assign the action.payload to the posts and then you can access it

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

    default:
      return posts;
  }
}; 

Upvotes: 0

Related Questions