State management

with Apollo Client

About Eevis

She/Her

Why this topic?

Query, Mutation, Subscription

Schema

type Witch {
    name: String
    house: String 
    wand: String
    patronus: String
    age: Int
}

Resolvers

const resolvers = {
  Query: {
    witch(parent, args, context, info) {
      // the logic for finding the witch
      return find(witch, { id: args.id });
    },
  },
}

Storing and Interacting with the State

Virtual Fields

Query

const typeDefs = gql`            
  extend type Spell {
    isSelected: Boolean
  }
`

const SpellResolver = {
  isSelected: (spell: Spell) =>
    spell.isSelected === undefined ? 
      false : spell.isSelected,
}

const resolvers = {
  Spell: SpellResolver,
}

Query

query spells($path: String) {
  spells @rest(type: "Spell", path: $path) {
    id
    spell
    type
    effect
    isSelected @client
  }
}

Mutation

const Mutation = {
 setSpellSelect: 
  (parent, args, { cache, getCacheKey }) => {
   const id = getCacheKey({ 
    __typename: 'Spell', 
    id: args.id 
   })
   const fragment = gql`
    fragment SpellSelected on Spell {
     isSelected @client
    }
   `
   const spell = cache.readFragment({ fragment, id })
   const data = { ...spell, isSelected: !spell.isSelected}
   cache.writeFragment({ id, data })
 }
}

Mutation

const resolvers = {
  Spell: SpellResolver,
  Mutation
}

Mutation

mutation toggleSpellSelect($id: ID) {
  setSpellSelect(id: $id) @clint {
    id
  }
}

Local data

Warning: In video there is flashing as colors change from black to white

Setup

cache.writeData({
  data: {
    theme: {
      mode: 'light',
      __typename: 'Theme'
    }
  }
})

Query

const typeDefs = gql`
  //...
  
  type Theme {
    mode: String
    __typename: String
  }
  
  extend type Query {
    theme: Theme
  }
`

Query

query getTheme {
  theme @client {
    mode
  }
}

Mutation

const Mutation = {
  //...
  setTheme: (_: any, __: any, { cache }: Context) => {
    const query = GET_THEME;
    const prev = cache.readQuery({ query });
    const data = {
      ...prev,
      theme: {
        ...prev.theme,
        mode: prev.theme.mode === 'light' ? 
              'dark' : 'light',
      },
    };
    cache.writeQuery({ query, data });
  },
};

GET_THEME

query getTheme {
  theme @client {
    mode
  }
}

Mutation

const Mutation = {
  //...
  setTheme: (_: any, __: any, { cache }: Context) => {
    const query = GET_THEME;
    const prev = cache.readQuery({ query });
    const data = {
      ...prev,
      theme: {
        ...prev.theme,
        mode: prev.theme.mode === 'light' ? 
              'dark' : 'light',
      },
    };
    cache.writeQuery({ query, data });
  },
};

Mutation

mutation setTheme {
  setTheme @client {
    mode
  }
}

Use Local Resolvers

Thank You!

Links

State Management with Apollo Client

By Eevis Panula

State Management with Apollo Client

  • 1,130