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/AddFace.js
2018-04-08 14:30:36 +12:00

65 lines
2 KiB
JavaScript

import React from "react";
import gql from "graphql-tag";
import { Mutation } from "react-apollo";
import IMPORT_PERSON from "../queries/import_person";
import LIST_PEOPLE from "../queries/list_people";
class AddFace extends React.Component {
// I extracted the cache updating logic from the JSX because there were too
// many nested braces and it was making me confused.
cacheUpdater(cache, { data: { importPerson } }) {
let { people } = cache.readQuery({ query: LIST_PEOPLE });
// If the person already exists in the cache then replace them with the new data.
let existingPersonIndex = people.findIndex(person => person.username === importPerson.username);
if (existingPersonIndex >= 0) {
people.splice(existingPersonIndex, 1, importPerson);
}
// Otherwise add them to the cache.
else {
people = people.concat([importPerson]);
}
cache.writeQuery({
query: LIST_PEOPLE,
data: { people: people }
});
}
render() {
let input;
return (
<Mutation
mutation={IMPORT_PERSON}
update={this.cacheUpdater}>
{(importPerson, { data }) => (
<div className="col-sm-3 mb-3">
<div className="card">
<div className="card-header">
<h5 className="card-title">Add Face</h5>
</div>
<div className="card-body">
<form onSubmit={e => {
e.preventDefault();
importPerson({ variables: { username: input.value } });
input.value = "";
}}>
<div className="form-group">
<label htmlFor="username">Github Username</label>
<input type="text" name="username" className="form-control" ref={node => input = node} />
</div>
<input type="submit" className="btn btn-primary" value="Add" />
</form>
</div>
</div>
</div>
)}
</Mutation>
);
}
}
export default AddFace;