This repository has been archived on 2024-06-24. You can view files and clone it, but cannot push or open issues or pull requests.
graphql-lightning-talk/assets/js/components/Gallery.js

50 lines
1.4 KiB
JavaScript
Raw Normal View History

import React from "react";
import gql from "graphql-tag";
import { Query } from "react-apollo";
import Person from "./Person";
import AddFace from "./AddFace";
import LIST_PEOPLE from "../queries/list_people";
import PERSON_ADDED from "../queries/person_added";
class Gallery extends React.Component {
// Uses Apollo's `subscribeToMore` callback to subscribe to the `personAdded`
// subscription and update our local data with the new data.
doSubscription(subscribeToMore) {
subscribeToMore({
document: PERSON_ADDED,
updateQuery: ({ people }, { subscriptionData }) => {
let newPerson = subscriptionData.data.personAdded;
let existingPersonIndex = people.findIndex(person => person.username === newPerson.username);
if (existingPersonIndex >= 0) {
people.splice(existingPersonIndex, 1, newPerson);
}
else {
people = people.concat([newPerson]);
}
return { people };
}
});
}
render() {
return (
<div className="row">
<Query query={LIST_PEOPLE}>
{({ subscribeToMore, loading, data }) => {
if (loading) return null;
this.doSubscription(subscribeToMore);
return data.people.map((person, key) => (<Person person={person} key={key} />));
}}
</Query>
<AddFace />
</div>
);
}
}
export default Gallery;