Skip to content

Commit

Permalink
A full example of creating Relay environment in Relay Environment Pro…
Browse files Browse the repository at this point in the history
…vider 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
  • Loading branch information
alunyov authored and facebook-github-bot committed Aug 24, 2023
1 parent c320a89 commit 9a1ea37
Showing 1 changed file with 41 additions and 2 deletions.
43 changes: 41 additions & 2 deletions website/docs/api-reference/hooks/relay-environment-provider.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
<RelayEnvironmentProvider environment={Environment}>
<RelayEnvironmentProvider environment={environment}>
<App />
</RelayEnvironmentProvider>
);
Expand Down

0 comments on commit 9a1ea37

Please sign in to comment.