react-hooksapolloapollo-clientreact-cookie

How to trigger React Hook in Apollo Local State


So... I'm using Apollo for local state management in my React app. I'm also using react-cookie (which relies on react hooks internally).

I'd like to do something pretty basic:

const logout = async (_, args, {cache}) => {
  const cookies = new Cookies()
  cookies.removeCookie (`auth`)
  cache.writeData ({data: {isAuthenticated: false}})
}

Problem is since I'm doing this outside a component, I can't use useCookies and hence my components never get an update that it's been removed.

Thoughts?

I really don't want to have to choose between putting my state logic into a resolver and using React hooks. And I'm guessing the same thing would apply for redux.

Cheers!


Solution

  • The only benefit to having the same state duplicated across both your cookies and component state (which is what this library does) is reactivity -- doing so will allow your components to update automatically if the cookies change. If you don't need that functionality, you're better off just using some library that doesn't utilize React-specific features, like js-cookie. Even if you need to listen for changes in cookies, you can do so without using hooks using a library like universal-cookie, which is what react-cookie uses under the hood.

    If you're bent on using react-cookie, then your logout mutation will need to only update local state, and you'll need to extract the combined logic into a separate hook. Something like:

    function useLogout = () => {
      const [updateLocalState] = useMutation(LOGOUT_MUTATION)
      const [removeCookie] = useCookies(['auth'])
      return async () => {
        await updateLocalState()
        removeCookie()
      }  
    }