Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adding "selected currencies" reactive var example #362

Merged
merged 2 commits into from
Oct 3, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 38 additions & 19 deletions examples/web/src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import React from 'react';
import { render } from 'react-dom';

import { ApolloProvider, ApolloClient } from '@apollo/client';
import { Query } from '@apollo/client/react/components';
import { ApolloProvider, ApolloClient, useQuery, makeVar, useReactiveVar } from '@apollo/client';
import gql from 'graphql-tag';
import { InMemoryCache } from '@apollo/client/core';
import { CachePersistor } from 'apollo3-cache-persist';
Expand Down Expand Up @@ -46,23 +45,43 @@ const ratesGQL = gql`
}
`;

const ExchangeRates = () => (
<Query query={ratesGQL} fetchPolicy="network-only">
{(result) => {
const { error, data, loading } = result;
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;

return data.rates.map(({ currency, rate }) => (
<div key={currency}>
<p>
{currency}: {rate}
</p>
</div>
));
}}
</Query>
);
const selectedCurrenciesVar = makeVar<String[]>([]);

const ExchangeRates = () => {
const selectedItems: String[] = useReactiveVar(selectedCurrenciesVar);
const { error, data, loading } = useQuery(ratesGQL, { fetchPolicy: "network-only" });

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

const toggleSelectedCurrency = (currency) => {
let newSelectedItems: String[] = [];

if (selectedItems.some(i => i === currency))
newSelectedItems = selectedItems.filter(i => i !== currency);
else
newSelectedItems = [...selectedItems, currency]

selectedCurrenciesVar(newSelectedItems);
}

return data.rates.map(({ currency, rate }) => {
const isCurrencySelected = selectedItems.some(i => i === currency);

return (
<div key={currency}>
<label>
<input
checked={isCurrencySelected}
type="checkbox" id="currency" name="currency"
onChange={() => toggleSelectedCurrency(currency)}
/>
{`${currency}: ${rate}`}
</label>
</div>
)
});
};

createClient().then(client => {
const App = () => (
Expand Down