Skip to content

Commit

Permalink
attempt to reproduce apollographql/apollo-client#6858
Browse files Browse the repository at this point in the history
  • Loading branch information
brainkim committed Jun 23, 2021
1 parent 198c88a commit e684451
Showing 1 changed file with 33 additions and 19 deletions.
52 changes: 33 additions & 19 deletions src/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ import {
GraphQLObjectType,
GraphQLID,
GraphQLString,
GraphQLFloat,
GraphQLList,
} from 'graphql';
const PersonType = new GraphQLObjectType({
name: 'Person',
fields: {
id: { type: GraphQLID },
name: { type: GraphQLString },
updated: { type: GraphQLFloat },
},
});

Expand All @@ -25,7 +27,9 @@ const QueryType = new GraphQLObjectType({
fields: {
people: {
type: new GraphQLList(PersonType),
resolve: () => peopleData,
resolve: () => {
return peopleData.map((person) => ({...person, updated: Date.now()}));
},
},
},
});
Expand Down Expand Up @@ -63,7 +67,7 @@ function delay(wait) {
const link = new ApolloLink(operation => {
return new Observable(async observer => {
const { query, operationName, variables } = operation;
await delay(300);
await delay(operationName === 'addPerson' ? 3000 : 300);
try {
const result = await graphql(
schema,
Expand Down Expand Up @@ -99,6 +103,7 @@ const ALL_PEOPLE = gql`
people {
id
name
updated
}
}
`;
Expand All @@ -112,17 +117,24 @@ const ADD_PERSON = gql`
}
`;

function PeopleList() {
const { loading, data } = useQuery(ALL_PEOPLE, { pollInterval: 1000 });
return loading ? (
<p>Loading…</p>
) : (
<ul>
{data?.people.map(person => (
<li key={person.id}>{person.name} ({person.updated})</li>
))}
</ul>
);
}

function App() {
const [name, setName] = useState('');
const {
loading,
data,
} = useQuery(ALL_PEOPLE);

const [addPerson] = useMutation(ADD_PERSON, {
update: (cache, { data: { addPerson: addPersonData } }) => {
update(cache, { data: { addPerson: addPersonData } }) {
const peopleResult = cache.readQuery({ query: ALL_PEOPLE });

cache.writeQuery({
query: ALL_PEOPLE,
data: {
Expand Down Expand Up @@ -152,23 +164,25 @@ function App() {
/>
<button
onClick={() => {
addPerson({ variables: { name } });
addPerson({
variables: { name },
optimisticResponse: {
addPerson: {
id: null,
name: `${name} (optimistic)`,
__typename: 'Person',
updated: Date.now(),
},
},
});
setName('');
}}
>
Add person
</button>
</div>
<h2>Names</h2>
{loading ? (
<p>Loading…</p>
) : (
<ul>
{data?.people.map(person => (
<li key={person.id}>{person.name}</li>
))}
</ul>
)}
<PeopleList />
</main>
);
}
Expand Down

0 comments on commit e684451

Please sign in to comment.