RelayEnvironmentProvider
RelayEnvironmentProvider
このコンポーネントは、React Context で Relay 環境を設定するために使用されます。通常、アプリケーション全体の Relay 環境を設定するため、このコンポーネントのインスタンスを 1 つだけ アプリケーションの一番のルートでレンダリングする必要があります
const React = require('React');
const {
Store,
RecordSource,
Environment,
Network,
Observable,
} = require("relay-runtime");
const {RelayEnvironmentProvider} = require('react-relay');
/**
* Custom fetch function to handle GraphQL requests for a Relay environment.
*
* This function is responsible for sending GraphQL requests over the network and returning
* the response data. It can be customized to integrate with different network libraries or
* to add authentication headers as needed.
*
* @param {RequestParameters} params - The GraphQL request parameters to send to the server.
* @param {Variables} variables - Variables used in the GraphQL query.
*/
function fetchFunction(params, variables) {
const response = fetch("http://my-graphql/api", {
method: "POST",
headers: [["Content-Type", "application/json"]],
body: JSON.stringify({
query: params.text,
variables,
}),
});
return Observable.from(response.then((data) => data.json()));
};
/**
* Creates a new Relay environment instance for managing (fetching, storing) GraphQL data.
*/
function createEnvironment() {
const network = Network.create(fetchFunction);
const store = new Store(new RecordSource());
return new Environment({ store, network });
}
const environment = createEnvironment();
function Root() {
return (
<RelayEnvironmentProvider environment={environment}>
<App />
</RelayEnvironmentProvider>
);
}
module.exports = Root;
プロパティ
environment
: React Context で設定する Relay 環境。このプロバイダーコンポーネントの子孫で使用されるuseLazyLoadQuery
やuseFragment
などの Relay Hooks は、ここで指定された Relay 環境を使用します
このページは役に立ちましたか?
ほんの少しの質問に 答えてもらうことで、サイトをもっと改善するのに役立ててください.