2
votes

How do you pass match.params in a Route to the new Apollo query component? I'm trying to take a React component build pre-Apollo 2.1 and use the new query components to learn how to use them.

My code before:

const Post = ({ data: { loading, error, post } }) => {
  if (error) return <h1>Error fetching the post!</h1>
  if (!loading) {
    return (
      <article>
        <h1>{post.title}</h1>
        <div className='Post-placeholder'>
          <img
            alt={post.title}
            src={`https://media.graphcms.com/resize=w:650,h:366,fit:crop/${post.coverImage.handle}`}
          />
        </div>
        <Markdown
          source={post.content}
          escapeHtml={false}
        />
      </article>
    )
  }
  return <h2>Loading post...</h2>
}

export const singlePost = gql`
  query singlePost($slug: String!) {
    post: Post(slug: $slug) {
      id slug title
      coverImage { handle }
      content dateAndTime
    } }`

export default graphql(singlePost, {
  options: ({ match }) => ({
    variables: {
      slug: match.params.slug
    }
  })
})(Post)

Here is the new code:

const Post = (slug) => (
  <Query query={singlePost} variables={{slug: slug.match.params.slug}}>
    {({ loading, error, post }) => { 
      if (loading || !post) return <h2>Loading post...</h2>
      if (error) return <h1>Error fetching the post!</h1>
      return (
        <article>
        <h1>{post.title}</h1>
        <div className='Post-placeholder'>
          <img
            alt={post.title}
            src={`https://media.graphcms.com/resize=w:650,h:366,fit:crop/${post.coverImage.handle}`}
          />
        </div>
        <Markdown
          source={post.content}
          escapeHtml={false}
        />
      </article>
      )
    }}
  </Query>
)

export const singlePost = gql`
      query singlePost($slug: String!) {
        post: Post(slug: $slug) {
          id slug title
          coverImage { handle }
          content dateAndTime
        } }`

export default Post;

I console.log post get an empty object, I console.log slug.match.params.slug I get the slug for the post that was passed by React-router. No errors in the console either, I get the loading screen then a black page. Also Apollo Dev tool shows the data from the query in the cache.

1

1 Answers

1
votes

I think it should be data, instead of post in the render callback.

  <Query query={singlePost} variables={{slug: slug.match.params.slug}}>
    {({ loading, error, data /* <=== This one */ }) => {
      console.log(data.post); // I think your post will be in data.post