You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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;
The text was updated successfully, but these errors were encountered:
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.The text was updated successfully, but these errors were encountered: