apollo icon indicating copy to clipboard operation
apollo copied to clipboard

Full-stack tutorial -> incorrect usage of cache.modify

Open Mikilll94 opened this issue 4 years ago • 1 comments

Intended outcome: In the full-stack tutorial in the docs, the cache.modify function is used incorrectly. If you run the app from the tutorial you will see that this function:

const [mutate, { loading, error }] = useMutation(
    CANCEL_TRIP,
    {
      variables: { launchId: id },
      update(cache, { data: { cancelTrip } }) {
        // Update the user's cached list of trips to remove the trip that
        // was just canceled.
        const launch = cancelTrip.launches[0];
        cache.modify({
          id: cache.identify({
            __typename: 'User',
            id: localStorage.getItem('userId'),
          }),
          fields: {
            trips(existingTrips) {
              const launchRef = cache.writeFragment({
                data: launch,
                fragment: gql`
                  fragment RemoveLaunch on Launch {
                    id
                  }
                `
              });
              return existingTrips.filter(
                (tripRef: Reference) => tripRef === launchRef
              );
            }
          }
        });
        // @ts-ignore
        console.log("CACHE", cache.data.data);
      }
    }
  );

removes from the cache all trips assigned to a user. Instead this function should only remove the trip which was cancelled by the user.

https://www.apollographql.com/docs/tutorial/local-state/#enable-cart-and-booking-modifications

Actual outcome: Only cancelled trip should be removed from the cache.

How to reproduce the issue:

  1. Clone this repo: https://github.com/apollographql/fullstack-tutorial.git
  2. Run client and server from the final folder in separate terminals.
  3. Add at least 2 trips to the cart.
  4. Book all trips from the cart.
  5. Go to the profile page and cancel one trip (does not matter which one).
  6. Check the User object in the cache (using i.e. Apollo devtools). The trip list assigned to the user is empty. Screenshot 2021-04-19 at 15 51 36

Versions

System: OS: macOS 11.2.3 Binaries: Node: 14.15.5 - /usr/local/bin/node Yarn: 1.22.10 - /usr/local/bin/yarn npm: 7.5.4 - /usr/local/bin/npm Browsers: Chrome: 90.0.4430.72 Firefox: 86.0 Safari: 14.0.3

Mikilll94 avatar Apr 19 '21 13:04 Mikilll94

Thanks for noticing this strange code and letting us know about it @Mikilll94!

I've opened two PRs to fix the docs and the tutorial code:

  • https://github.com/apollographql/apollo/pull/1145
  • https://github.com/apollographql/fullstack-tutorial/pull/213

benjamn avatar Apr 19 '21 23:04 benjamn