From 9a1ea37e1af3c1b1e35d15910a27679708136a36 Mon Sep 17 00:00:00 2001 From: Andrey Lunyov Date: Thu, 24 Aug 2023 13:20:18 -0700 Subject: [PATCH] A full example of creating Relay environment in Relay Environment Provider docs Summary: Current example just have this for the creating of the environment: ``` const Environment = createNewEnvironment(); ``` And it's not immediately clear where to get that function or what this function even supposed to do. This diff provides an example implementation of a basic "create environment" functionality. Reviewed By: voideanvalue Differential Revision: D48647447 fbshipit-source-id: db966b9d45c12878ba5ecd6bd88b4b71422a0afd --- .../hooks/relay-environment-provider.md | 43 ++++++++++++++++++- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/website/docs/api-reference/hooks/relay-environment-provider.md b/website/docs/api-reference/hooks/relay-environment-provider.md index ca05fd7e74018..882e457cace88 100644 --- a/website/docs/api-reference/hooks/relay-environment-provider.md +++ b/website/docs/api-reference/hooks/relay-environment-provider.md @@ -16,14 +16,53 @@ This component is used to set a Relay environment in React Context. Usually, a * ```js const React = require('React'); +const { + Store, + RecordSource, + Environment, + Network, + Observable, +} = require("relay-runtime"); const {RelayEnvironmentProvider} = require('react-relay'); -const Environment = createNewEnvironment(); +/** + * 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 ( - + );