I have a basic graphql/apollo sandbox application.
The graphql server can return a list of books
const books = [
{
id: 1,
title: "Harry Potter and the Sorcerer's stone",
author: 'J.K. Rowling',
},
{
id: 2,
title: 'Jurassic Park',
author: 'Michael Crichton',
},
];
// The GraphQL schema in string form
const typeDefs = `
type Query { books: [Book] }
type Book { title: String, author: String, id: ID }
`;
and the client fetch them
import React from 'react';
import './App.css';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
const elements = new Set();
const TodoApp = ({ data, data: { books, loading, error}}) => {
if (loading) {
return <div>Loading</div>
}
if (error) {
return <div>Error {error}</div>
}
return (
<ul>
{books.map((book, i) => {
console.log(elements.has(book) ? `has` : `don't have`, book);
elements.add(book);
return (
<MyLiPureComponent key={book.id} book={book} />
)
})}
</ul>
);
}
const query = gql`{
books {
id
title
author
}
}`;
export default graphql(query)(TodoApp);
This code keeps track of every book's reference and output if they are already tracked or not. When the list of books is requested over and over again, the output shows, every time, all books are brand new objects.
I'd like to avoid that and have apollo create any book only once (then forward those objects to my component). I want to be able to rely on react's PureComponent (explained here) later on, so if the reference are never the same, it would just be pointless.