Phil Holden
Phil Holden

Reputation: 304

In Relay how should I get from global Id to local Id on client?

On the server fromGlobalId(id) is used to get from a relay global Id to the actual Id on the on the object.

At the moment I am doing the same on the client i.e.

javascript import { fromGlobalId } from 'graphql-relay' fromGlobalId(accounts[0].id)

It gives the correct result:

Object {type: "Account", id: "0"}

but should I be importing graphql-relay on client is there a way I can do this with just react-relay?

Upvotes: 1

Views: 1652

Answers (1)

nethsix
nethsix

Reputation: 900

If you need the object type and id, Perhaps it is better to just pass it back in the GraphQL response?

On the server-side, define in your GraphQL schema:

var accountType = new GraphQLObjectType({
  name: 'Account',
  description: 'An account',
  fields: () => ({
    id: globalIdField('Account'),
    objectType: {
      type: GraphQLString,
      description: 'Object type',
    }
    objectId: {
      type: GraphQLString,
      description: 'Object ID',
    },
  }),
  interfaces: [nodeInterface],
});

On the client-side, just query for objectType, objectId:

fragments: {
  account: () => Relay.QL`
    fragments on Account {
      id,
      objectType,
      objectId,
    }
  `
}

Upvotes: 1

Related Questions