Mazino
Mazino

Reputation: 356

Type Error when destructuring elements In ReactJS

Problem

After I query my objects from GraphQl server, on console logging data I get my objects in the console but when I destructure it in a way data: { getPosts : posts } it returns a type error and when I try to map over data only it returns data.map is not a function

The Code

const {loading, data: {getPosts: posts} } = useQuery(FETCH_POSTS); // Here is the error

return(
             {loading ? (
                   <h1>Loading...</h1>
               ) : (
                   posts && posts.map(post => (
                       <Grid.Column key={post.id}> 
                           <PostCard post={post} />
                       </Grid.Column>
                    ))
               )}
)

The TypeError

TypeError

The data on console.log(data)

Object Error

Upvotes: 0

Views: 618

Answers (2)

Clarity
Clarity

Reputation: 10873

That kind of destructuring is not gonna work, because at the time when it happens data is still undefined. So you'll need to wait for it to load.

  const { loading, data } = useQuery(FETCH_POSTS);

  return loading ? (
    <h1>Loading...</h1>
  ) : (
    data.getPosts.map((post) => (
      <Grid.Column key={post.id}>
        <PostCard post={post} />
      </Grid.Column>
    ))
  );

Upvotes: 1

eloyra
eloyra

Reputation: 529

You need to await the async request for the data to be ready so that it can be destructured.

Upvotes: 0

Related Questions