Skip to content

Errors #24

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

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
21 changes: 6 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,22 +1,13 @@

## Description

This is a simple Create React App demonstrating a bug (or potentially expected behavior) where unmounting a component that
has a "fetchPolicy" of "cache-and-network" and "nextFetchPolicy" of "cache-first" essentially resets the fetchPolicy state,
such that returning to the component utilizes the "fetchPolicy" rather than the "nextFetchPolicy", which means the query will
re-fire even though the data exists in cache.

The way I work around this is wrapping my useQuery utilization and keeping a global tracker of whether the query has been run
once. If it has, I force the fetchPolicy to be "cache-first", this feels like a hack and I wonder if this behavior is expected
or is a bug w/Apollo.

## Duplicating

```sh
npm install
npm run start
```

1. Click "Click me to unmount to another route"
2. Click "Click me to go back to home and see the query re-fire"
3. You'll see the "loading.." indicator, which indicates the query has re-fired.
1. Navigate to localhost:3000/124891248912491
2. Notice that you will see an error from "useQuery", this is expected.
3. Click the button to return home where there is no movie query parameter.
4. Click the button to navigate to valid movie.
5. Note a flicker where the error message will temporarily render, and note in the console that the error is still present from the "useQuery" return value.
6. The error then disappears once the fetch is complete. However, since the variable set is distinct at the point of #4, the "useQuery" state should be empty and there should be no cached value for this query yet.
116 changes: 89 additions & 27 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"version": "0.1.0",
"private": true,
"dependencies": {
"@apollo/client": "^3.2.5",
"@apollo/client": "^3.3.20",
"@testing-library/jest-dom": "^5.11.5",
"@testing-library/react": "^11.1.2",
"@testing-library/user-event": "^12.2.2",
Expand Down
27 changes: 11 additions & 16 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,16 @@

const { ApolloServer, gql } = require('apollo-server-express');
const express = require('express');
const { v4 } = require('uuid');

const simpleSchema = gql`
type Query {
movies(movieIds: [Int!]): [Movie!]!
requestDetails: RequestDetails!
movie(movieId: ID!): Movie
}

type Movie {
movieId: Int!
internalTitle: String!
}

type RequestDetails {
id: String!
}
`;

const fakeMovies = {
Expand All @@ -37,8 +31,8 @@ const fakeMovies = {
internalTitle: 'some movie 80229867',
},
80025678: {
movieId: 80229867,
internalTitle: 'some movie 80229867',
movieId: 80025678,
internalTitle: 'some movie 80025678',
},
80229865:{
movieId: 80229865,
Expand Down Expand Up @@ -70,15 +64,16 @@ const server = new ApolloServer({
typeDefs: simpleSchema.loc.source.body,
resolvers: {
Query: {
movies: (root, args, context, info) => {
const movieIds = args.movieIds;
return new Promise(resolve => {
setTimeout(() => {
resolve(movieIds.map(movieId => fakeMovies[movieId]));
}, 2000);
movie: (root, args, context, info) => {
return new Promise((resolve, reject) => {
if (fakeMovies[args.movieId]) {
resolve(fakeMovies[args.movieId]);
return;
}
reject('Unauthorized access');
});
},
},
}
}
});
const app = express();
Expand Down
86 changes: 43 additions & 43 deletions src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,70 +1,70 @@
import React from "react";
import React, { useCallback } from "react";
import ReactDOM from "react-dom";
import gql from "graphql-tag";
import { BrowserRouter, Link, Route, Switch } from 'react-router-dom';
import { BrowserRouter, Route, Switch, useHistory, useParams } from 'react-router-dom';

import { ApolloClient, HttpLink, InMemoryCache, ApolloProvider, useQuery} from "@apollo/client";

const client = new ApolloClient({
cache: new InMemoryCache(),
link: new HttpLink({
uri: "/graphql"
}),
defaultOptions: {
watchQuery: {
fetchPolicy: 'cache-and-network',
nextFetchPolicy: 'cache-first',
}
}
});

// Removing "requestDetails" from here will make the React warnings go away.
const GET_MOVIES = gql(`
query GetMovies($movieIds: [Int!]!) {
movies(movieIds: $movieIds) {
const GET_MOVIE = gql(`
query GetMovie($movieId: ID!) {
movie(movieId: $movieId) {
movieId
internalTitle
}
}
`);

function FooBarPage() {
return <div>
<h1>Foobar Route</h1>
<Link to={'/'}>Click me to go back to home and see the query re-fire</Link>
</div>
}

function HomePage() {
const { data, loading } = useQuery(GET_MOVIES, {
variables: { movieIds: [80117456, 80025678] }
const { movieId } = useParams() as { movieId?: string };
const { data, error } = useQuery(GET_MOVIE, {
variables: {
movieId
},
skip: !movieId,
});
return (
<div>
<h1>Home Page Route</h1>
<Link to={'/foobar'}>Click me to unmount to another route</Link>
{(() => {
if (loading) {
return <div>loading (we only want to see this on first mount)...</div>
}
<ul>
{data.movies.map((movie: any) => {
return <div key={movie.movieId}>
<div>{movie.internalTitle}</div>
</div>;
})}
</ul>
})()}
</div>
);
}

console.log('home page rendering', movieId, error);
const history = useHistory();
const onNavigateToValidRoute = useCallback(()=> {
history.push('/80057281');
}, [history]);

const onNavigateHome = useCallback(()=> {
history.push('/');
}, [history]);

if (!movieId) {
return <div>
<h1>Home Page -- No Movie ID in URL</h1>
<button onClick={onNavigateToValidRoute}>Click me to navigate to a valid movie id where the error will persist.</button>
</div>
}

return <div>
<h1>Movie Detail Page</h1>
<button onClick={onNavigateHome}>Click me to navigate home</button>
{error && <div>{error.message}</div>}
{(() => {
if (!data) {
return <div>we have no movie...</div>
}
return <div key={data.movie.movieId} style={{ display: 'flex', flexDirection: 'row'}}>
<div>{data.movie.internalTitle}</div>
</div>
})()}
</div>
}
function App() {
return <ApolloProvider client={client}>
<BrowserRouter>
<Switch>
<Route exact path={'/'} component={HomePage} />
<Route exact path={'/foobar'} component={FooBarPage} />
<Route exact path={'/:movieId?'} component={HomePage} />
</Switch>
</BrowserRouter>
</ApolloProvider>
Expand Down