Skip to content
Advertisement

Send data between components in ReactJs using Apollo Client

According to the documentation, GraphQl provides state management like Redux. I have 2 components. In the Component1 i get data from the server using AppoloClient, it works ok, and in the Component2 i want to read data from the cache(store).

//Component1
import React from "react";
import { gql, useQuery } from "@apollo/client";

const EXCHANGE_RATES = gql`
  query GetExchangeRates {
    rates(currency: "EUR") {
      currency
    }
  }
`;

const Component1 = () => {
  const { loading, error, data } = useQuery(EXCHANGE_RATES);
  console.log("component1", data);

  return <div>Component1</div>;
};

export default Component1;

//Component2
import React from 'react';
import {gql} from "@apollo/client";
import {client} from "./App";

const Component2 = () => {
    const info = client.readQuery({
        query: gql`
            query EXCHANGE_RATES {
                rates(currency: "EUR") {
                    currency
                }
            }
        `,
    });
    console.log('component2',info);
    return (
        <div>
          component2
        </div>
    );
};

export default Component2;

Issue: I can get data in component 1, but when I try to read data from component 2, I get undefined.
Question: How to solve this to be able to read data that is fetched in component 1, in component 2? Also how in GraphQl and Apollo client to pass an object for example in the cache, and to read this in component 1(like redux functionality)?
demo: https://codesandbox.io/s/empty-sun-symv6?file=/src/App.js

Advertisement

Answer

Apollo provides client-side state handling which can be set up to handle your client site state in the same we you do it with your server-side state.

In your example this is not what you want. Recently there is a noticeable shift in the react community that server side data should not be stored in your global state handling tool of choice. Your fetching tool (in your case apollo) should handle this by caching the responses.

To solve your problem, where both components are using the exact same query, you should just do that. Run the query twice and let apollo handle the caching. So you could pull out the query to a query file or just create a useRates hook and import that in your component to even better share the logic between your components.

To answer why your approach is not working you have to understand that your lookup in the cache is happening at a time before your request has even finished and that this cache look up is not “reactive”.

Edit: I just got this out fast to provide a starting point and can clean this up later if things got cleared up.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement