An example of usage GraphQL and React
Make query GetExchangeRates
here https://48p1r2roz4.sse.codesandbox.io
query GetExchangeRates {
rates(currency: "USD") {
currency
rate
}
}
$ npx create-react-app my-app --template typescript
$ yarn add @apollo/client graphql
import {
ApolloClient,
InMemoryCache,
ApolloProvider
} from "@apollo/client";
const client = new ApolloClient({
uri: 'https://48p1r2roz4.sse.codesandbox.io',
cache: new InMemoryCache()
});
render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
document.getElementById('root'),
);
import React from 'react';
import './App.css';
import {gql, useQuery} from "@apollo/client";
const EXCHANGE_RATES = gql`
query GetExchangeRates {
rates(currency: "USD") {
currency
rate
}
}
`;
function ExchangeRates() {
const {loading, error, data} = useQuery(EXCHANGE_RATES);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
return data.rates.map(({currency, rate}: { currency: string, rate: number }) => (
<div key={currency}>
<p>
{currency}: {rate}
</p>
</div>
));
}
function App() {
return (
<div>
<h2>get "Currency Exchange Rates" using Apollo & Graphql</h2>
<ExchangeRates/>
</div>
);
}
export default App;