reactjsfrontendapollo-clientreact-apolloreact-apollo-hooks

cache.writeData is not a function -> inMemoryCache error


I'm working with react and apollo client. i'm get confusing error and i can't find exactly the problem. i have the code.

import logo from './logo.svg';
import './App.css';
import Pages from './pages';
import GlobalStyles from './components/GlobalStyles';

import { ApolloClient, ApolloProvider, createHttpLink, InMemoryCache } from '@apollo/client';
import { setContext } from 'apollo-link-context';

const uri = process.env.REACT_APP_BASE_URL;
const httpLink = createHttpLink({ uri });
const authLink = setContext((_, { headers }) => {
    return {
        headers: {
            ...headers,
            authorization: localStorage.getItem('token') || ''
        }
    }
})
const cache = new InMemoryCache();

// configure Apollo Client
const client = new ApolloClient({
    link: authLink.concat(httpLink),
    cache,
    resolvers: {},
    connectToDevTools: true
})

const data = {
    isLoggedIn: !!localStorage.getItem('token')
}

//write the cache data on initial load

// here's the problem
cache.writeData({ data });

function App() {
    return (
        <ApolloProvider client={client}>
      <GlobalStyles/>
      <Pages/> 
    </ApolloProvider>
    );
}

export default App;

i got an error. enter image description here

i hope this error is cleared and removed. so it can loaded login data. any help will be appreciated. thank you.


Solution

  • from what I know you can't just write directly to the cache like that

    you should be using writeQuery to write to the cache. use the folowing link for more information on how to use it.

    https://www.apollographql.com/docs/react/caching/cache-interaction/

    if i'm wrong let me know then i can learn too