How to dispatch an ad-hoc query, with Relay?

本秂侑毒 提交于 2019-12-03 05:11:04

问题


I'm new to Relay, still trying to wrap my head around it. Based on my understanding, Relay ties queries to components. This way, you can say that a component needs to be provided x, y and z from the GraphQL server. Based on my understanding, the official react-relay library will dispatch those queries at the appropriate time, likely when the component is about to be rendered.

This all makes sense to me for straight forward use cases, such as simply displaying a list of data.

What I'm confused on how to do, though, is how to dispatch a query that may not quite fall into the category of something that would be tied to a component. A query such as one that attempts to fetch a user authentication session token, or something. This is my current situation: I'm trying to create a user sign in form that fetches a session token from GraphQL. I've got a parameterized GraphQL field that requires username and password arguments and will return a session token if they're valid. I just can't figure out how to use Relay to query for that session token.

I'd essentially just need to dispatch a query, and handle the response (place that session token into the React application state).

Any ideas?


回答1:


Relay's APIs are primarily focused on making it easy to fetch data for components, but Relay also supports ad-hoc queries. The API is relatively low-level, with distinct functions for fetching and reading data. Here's an example of how to fetch an ad-hoc query and access the response:

// Create a query with values for any variables:
var query = Relay.createQuery(Relay.QL`query ... `, {var: 'value'});
// Fetch any fields that have not yet been cached:
Relay.Store.primeCache({query}, readyState => {
  if (readyState.done) {
    // When all data is ready, read the data from the cache:
    var data = Relay.Store.readQuery(query)[0];
    /* access fields on `data` */
  }
});

If the data doesn't need to be synchronized with Relay's cache, you can also use a plain network request (XHR, fetch, etc) to send a plain string query to your GraphQL endpoint.




回答2:


It's honestly probably easiest to use a separate library. I use Lokka in my node projects and it's dead-simple and reliable.

// config
const Lokka = require('lokka').Lokka;
const Transport = require('lokka-transport-http').Transport;

const client = new Lokka({
  transport: new Transport('http://graphql-swapi.parseapp.com/')
});



// query
client.query(`
  {
    allFilms {
      films {
        ...${filmInfo}
      }
    }
  }
`).then(result => {
  console.log(result.allFilms.films);
});


来源:https://stackoverflow.com/questions/34053662/how-to-dispatch-an-ad-hoc-query-with-relay

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!