fetchQuery | Relay (original) (raw)

If you want to fetch a query outside of React, you can use the fetchQuery function from react-relay:

// You should prefer passing an environment that was returned from useRelayEnvironment()
const MyEnvironment = require('MyEnvironment');
const {fetchQuery} = require('react-relay');

fetchQuery(
  environment,
  graphql`
    query AppQuery($id: ID!) {
      user(id: $id) {
        name
      }
    }
  `,
  {id: 4},
)
.subscribe({
  start: () => {...},
  complete: () => {...},
  error: (error) => {...},
  next: (data) => {...}
});

If desired, you can convert the request into a Promise using **.toPromise()**. Note that toPromise will start the query and return a Promise that will resolve when the first piece of data returns from the server and cancel further processing. That means any deferred or 3D data in the query may not be processed. We generally recommend against using toPromise() for this reason.

const {fetchQuery} = require('react-relay');

fetchQuery(
  environment,
  graphql`
    query AppQuery($id: ID!) {
      user(id: $id) {
        name
      }
    }
  `,
  {id: 4},
)
.toPromise() // NOTE: don't use, this can cause data to be missing!
.then(data => {...})
.catch(error => {...};