When using the guide to make a LocalStorage Based Persistent Cache I am running into issues with the localStorageProvider running on the server resulting in errors. It would be nice for this document to elaborate on how to prevent this.
⨯ context/SWRConfigProvider.tsx (10:35) @ localStorage
⨯ ReferenceError: localStorage is not defined
at localStorageProvider (./context/SWRConfigProvider.tsx:12:36)
at provider (./context/SWRConfigProvider.tsx:25:27)
8 |
9 | // When initializing, we restore the data from `localStorage` into a map.
> 10 | const map = new Map(JSON.parse(localStorage.getItem('app-cache') || '[]'))
| ^
11 |
12 | // Before unloading the app, we write back all the data into `localStorage`.
13 | window.addEventListener('beforeunload', () => {
'use client'
import {ReactElement, useEffect, useState} from "react";
import { SWRConfig, Cache } from 'swr'
function localStorageProvider(): Cache<any> {
// When initializing, we restore the data from `localStorage` into a map.
const map = new Map(JSON.parse(localStorage.getItem('app-cache') || '[]'))
// Before unloading the app, we write back all the data into `localStorage`.
window.addEventListener('beforeunload', () => {
const appCache = JSON.stringify(Array.from(map.entries()))
localStorage.setItem('app-cache', appCache)
console.log("Saved Cache", map)
})
// We still use the map for write & read for performance.
return map as Cache<any>
}
const SWRConfigProvider = ({children} : {children: ReactElement[] | ReactElement}) => {
return (
<SWRConfig value={{ provider: localStorageProvider }}>
{children}
</SWRConfig>
)
}
export default SWRConfigProvider;
When using the guide to make a
LocalStorage Based Persistent Cache
I am running into issues with the localStorageProvider running on the server resulting in errors. It would be nice for this document to elaborate on how to prevent this.