Apollo Client The Ultimate Solution for State Management with GraphQL

Introduction to Apollo Client

Apollo Client is a powerful and flexible JavaScript library used to manage the state of a GraphQL application both on the client and the server-side. It enables developers to declaratively fetch and cache data, ensuring a more efficient and organized codebase.

Getting Started with Apollo Client


import { ApolloClient, InMemoryCache, gql } from '@apollo/client';

const client = new ApolloClient({
  uri: 'https://48p1r2roz4.sse.codesandbox.io',
  cache: new InMemoryCache()
});

// Querying data
client
  .query({
    query: gql`
      {
        rates(currency: "USD") {
          currency
          rate
        }
      }
    `
  })
  .then(result => console.log(result));

Setting Up Apollo Provider


import React from 'react';
import { ApolloProvider } from '@apollo/client';
import ReactDOM from 'react-dom';
import App from './App';
import { client } from './apolloClientSetup';

ReactDOM.render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>,
  document.getElementById('root')
);

Using useQuery Hook


import { useQuery, gql } from '@apollo/client';

const GET_RATES = gql`
  query GetRates($currency: String!) {
    rates(currency: $currency) {
      currency
      rate
    }
  }
`;

function ExchangeRates({ currency }) {
  const { loading, error, data } = useQuery(GET_RATES, {
    variables: { currency },
  });

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :({error.message}</p>;

  return (
    <div>
      {data.rates.map(({ currency, rate }) => (
        <div key={currency}>
          <p>{currency}: {rate}</p>
        </div>
      ))}
    </div>
  );
}

Example App with Apollo Client


import React from 'react';
import { ApolloProvider, InMemoryCache, ApolloClient } from '@apollo/client';
import ExchangeRates from './ExchangeRates';

const client = new ApolloClient({
  uri: 'https://48p1r2roz4.sse.codesandbox.io',
  cache: new InMemoryCache(),
});

function App() {
  return (
    <ApolloProvider client={client}>
      <div>
        <h2>My First Apollo App 🚀</h2>
        <ExchangeRates currency="USD" />
      </div>
    </ApolloProvider>
  );
}

export default App;

Conclusion

Apollo Client is an essential tool for managing GraphQL queries in modern web applications. The above examples demonstrate some of the basic functionalities and how to set up an application using various Apollo Client APIs. With these tools at your disposal, state management and data fetching becomes more straightforward and efficient.

Hash: 4b28cc17a12e931ceb500e40d55a69069684edc0f1b1a43a9ebbd5d972b11660

Leave a Reply

Your email address will not be published. Required fields are marked *