0

recently I've just started to read RTK Query's document in the redux.js.org and understood the doc's main project doesn't show the Posts in CodeSandbox and just [object Object] is obvioused except of the Posts list which should being loaded by the fake server included in the default project . secondly I couldn't managed the error in PostsList page (the Page which is included in the redux main project (simple social media)) .

features/posts/PostsList.js

 export const PostList = () => {
  const {
    data: posts = [],
    isSuccess,
    isLoading,
    isError,
    error,
  } = useGetPostsQuery()

  const orderedPosts = useMemo(() => {
    console.log(posts)
    const ordered = posts.posts.slice()
    ordered.sort((a, b) => b.date.localeCompare(a.date))
    return ordered
  }, [posts])

just got the [] as the posts value then this error appears "Cannot read properties of undefined (reading 'slice')"

and the whole the main project of redux is accessible right in this link rtk-query-basics

phry
  • 35,762
  • 5
  • 67
  • 81
Ali Bidjandy
  • 361
  • 6
  • 15

1 Answers1

0

I believe the problem is in the following line:

const ordered = posts.posts.slice()

It is trying to access a posts property on the posts array, which returns undefined (most likely a typo). This would explain the error message, as undefined is not an array, and therefore does not have a slice method.

To fix the problem, amend the line to look like this:

const ordered = posts.slice()
Sam McElligott
  • 306
  • 1
  • 4