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

前端 未结 2 404
醉话见心
醉话见心 2021-02-01 08:47

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 provid

相关标签:
2条回答
  • 2021-02-01 09:05

    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.

    0 讨论(0)
  • 2021-02-01 09:08

    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);
    });
    
    0 讨论(0)
提交回复
热议问题