LogoutManager
Logs out based on fetch responses. By default this is triggered by 401 (Unauthorized) status responses.
implements
LogoutManager
implements Manager
Usage
- React Web 16+
- React Web 18+
- React Native
- NextJS
/index.tsx
import { CacheProvider, LogoutManager } from '@rest-hooks/react';
import ReactDOM from 'react-dom';
const managers = [new LogoutManager(), ...CacheProvider.defaultProps.managers];
ReactDOM.render(
<CacheProvider managers={managers}>
<App />
</CacheProvider>,
document.body,
);
/index.tsx
import { CacheProvider, LogoutManager } from '@rest-hooks/react';
import ReactDOM from 'react-dom';
const managers = [new LogoutManager(), ...CacheProvider.defaultProps.managers];
ReactDOM.createRoot(document.body).render(
<CacheProvider managers={managers}>
<App />
</CacheProvider>,
);
/index.tsx
import { CacheProvider, LogoutManager } from '@rest-hooks/react';
import { AppRegistry } from 'react-native';
const managers = [new LogoutManager(), ...CacheProvider.defaultProps.managers];
const Root = () => (
<CacheProvider managers={managers}>
<App />
</CacheProvider>
);
AppRegistry.registerComponent('MyApp', () => Root);
pages/_app.tsx
import { CacheProvider, LogoutManager } from '@rest-hooks/react';
import { AppCacheProvider } from '@rest-hooks/ssr/nextjs';
import type { AppProps } from 'next/app';
const managers = [new LogoutManager(), ...CacheProvider.defaultProps.managers];
export default function App({ Component, pageProps }: AppProps) {
return (
<AppCacheProvider managers={managers}>
<Component {...pageProps} />
</AppCacheProvider>
);
}
Custom logout handler
import { unAuth } from '../authentication';
const managers = [
new LogoutManager({
handleLogout(controller) {
// call custom unAuth function we defined
unAuth();
// still reset the store
controller.resetEntireStore();
},
}),
...CacheProvider.defaultProps.managers,
];
tip
Use controller.invalidateAll to only clear part of the cache.
import { unAuth } from '../authentication';
const testKey = (key: string) => key.startsWith(`GET ${myDomain}`);
const managers = [
new LogoutManager({
handleLogout(controller) {
// call custom unAuth function we defined
unAuth();
// still reset the store
controller.invalidateAll({ testKey })
},
}),
...CacheProvider.defaultProps.managers,
];
Members
handleLogout(controller)
By default simply calls controller.resetEntireStore()
This should be sufficient if login state is determined by a user entity existance in the Rest Hooks store. However, you can override this method via inheritance if more should be done.
shouldLogout(error)
protected shouldLogout(error: UnknownError) {
// 401 indicates reauthorization is needed
return error.status === 401;
}