0

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

2

2 Answers 2

1

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>
    ))
  );
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.