0

I'm trying to inject a postId variable into a fragmentContainer.

I've started the project with the with-relay-modern example.

The variable $postId doesn't inject properly, so I used defaultValue: "UG9zdDoy" in the meantime, but the goal is to get the value of postId from props.

The page - singlePost.js

import React, { Component } from 'react'
import { graphql } from 'react-relay'
import withData from '_libs/withData'
import PostDetail from '_components/post_page/PostDetail'
import App from '_components/App'

class PostsPage extends Component {
  static displayName = `PostsPage`
  static getInitialProps ({ query }) {
    return { query }
  }

  render (props) {
    const { viewer } = this.props
    return (
          <div>
          {viewer ? <PostDetail {...this.props} 
                        postId={this.props.url.query.postId} 
                        viewer={viewer} 
                        relay={this.props.environment} /> : 'no viewer'}
          </div>
    )
  }
}

export default withData(PostsPage, {
  query: graphql`
    query singlePost_Query { 
      viewer { 
        ...PostDetail_viewer
      } 
    }`,
})

The component - postDetail.js

import React from 'react'
import PropTypes from 'prop-types'
import { createFragmentContainer, graphql } from 'react-relay'

const PostDetail = (props, {viewer}) => {
  return (
    <div>
      post
    </div>
  )
}

PostDetail.propTypes = {
  viewer: PropTypes.shape({
    post: PropTypes.shape({
      title: PropTypes.string.isRequired,
      description: PropTypes.string.isRequired,
      image: PropTypes.string.isRequired,
      creator: PropTypes.shape({
        firstName: PropTypes.string.isRequired,
        lastName: PropTypes.string.isRequired,
      }).isRequired,
    }),
  }).isRequired,
}

// postId only works with defaultValue, but I need to get it from props.
export default createFragmentContainer(
  PostDetail,
  graphql`
    fragment PostDetail_viewer on Viewer
    @argumentDefinitions(
      postId: {type: "String!", defaultValue: "UG9zdDoy"},
    )
    {
      post (postId: $postId) {
        title
        description
        image
        creator {
          firstName
          lastName
        }
      }
    }
  `,
)

Any idea how to achieve this? Deleting **defaultValue: "UG9zdDoy" ** and re-compiling gives the following error:

RelayCompilerScope: No value found for required argument $postId: String!

  • Possible duplicate of [Pass variables to fragment container in relay modern](https://stackoverflow.com/questions/44753480/pass-variables-to-fragment-container-in-relay-modern) – dobleUber Jan 15 '18 at 17:44
  • I had seen that post, but unfortunately it does not solve my issue. –  Jan 16 '18 at 09:18

0 Answers0