How to fetch and display item by id using Relay container, react-router and GraphQL

倾然丶 夕夏残阳落幕 提交于 2019-12-04 22:00:16

You need to pass the router variables to your fragment.

const ViewerQuery = {
  viewer: (Component, vars) => Relay.QL`
    query {
      viewer {
        ${Component.getFragment('viewer', vars)} # <-- this
      }
    }
  `
}

I copied this code detail from here: https://github.com/relay-tools/react-router-relay/issues/92#issuecomment-235641397

Then you can use the id variable in your component, but you need an initial value for id:

export default Relay.createContainer(CreativeEditComponent, {
  initialVariables: {
    id: ''
  },
  fragments: {
    viewer: () => Relay.QL`
        fragment on User {
          id,
          feature(id:$id) {
            id
            name
            description
          }
        }`
    }
});

And in schema.js define a field for your user type, that serves only one feature:

const userType = new GraphQLObjectType({
  name: 'User',
  description: 'A person who uses our app',
  fields: () => ({
    id: globalIdField('User'),
    feature: {
      type: featureType,
      description: 'feature',
      args: {
        id: {
          type: GraphQLString,
          description: 'The id of the feature'
        }
      },
      resolve: (_, args) => resolveGetFeature (args),
    },
    ...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!