Home > Mobile >  useSelector property returns undefined
useSelector property returns undefined

Time:11-16

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;

CodePudding user response:

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);

CodePudding user response:

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;
  }
}; 

CodePudding user response:

  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
  • Related