// your-app-name/src/fetchGraphQL.jsasyncfunctionfetchGraphQL(text, variables) {...// Fetch data from GitHub's GraphQL API:constresponse=awaitfetch('https://api.github.com/graphql', { method:'POST',..., body:JSON.stringify({ query: text, variables, }), });// Get the response as JSONreturnawaitresponse.json();}exportdefault fetchGraphQL;
2.3. Fetching GraphQL From React
// your-app-name/src/App.js...functionApp() {// We'll load the name of a repository, initially setting it to nullconst [name,setName] =useState(null);// When the component mounts we'll fetch a repository nameuseEffect(() => {let isMounted =true;fetchGraphQL(` query RepositoryNameQuery { # feel free to change owner/name here repository(owner: "facebook" name: "relay") { name } } `).then(response => {// Avoid updating state if the component unmounted before the fetch completes// ๋ฐ์ดํฐ ํจ์นญ์ด ์๋ฃ๋๊ธฐ ์ unMount ๋๋ ๊ฒฝ์ฐ ์ฒ๋ฆฌif (!isMounted) {return; }constdata=response.data;setName(data.repository.name); }).catch(error => {console.error(error); });return () => { isMounted =false; }; }, [fetchGraphQL]);// Render "Loading" until the query completesreturn ( <divclassName="App"> <headerclassName="App-header"> <p> {name !=null?`Repository: ${name}`:"Loading"} </p> </header> </div> );}exportdefault App;
Step 3. When To Use Relay (Relay ์ฌ์ฉํด ๋ฐ์ดํฐ ๊ฐ์ ธ์ค๊ธฐ)
// your-app-name/src/RelayEnvironment.jsimport {Environment, Network, RecordSource, Store} from'relay-runtime';import fetchGraphQL from'./fetchGraphQL';// Relay passes a "params" object with the query name and text. So we define a helper function// to call our fetchGraphQL utility with params.text.asyncfunctionfetchRelay(params, variables) {console.log(`fetching query ${params.name} with ${JSON.stringify(variables)}`);returnfetchGraphQL(params.text, variables);}// Export a singleton instance of Relay Environment configured with our network function:exportdefaultnewEnvironment({ network:Network.create(fetchRelay), store:newStore(newRecordSource()),});