-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add example using SWR to sync storage between tabs (#74)
- Loading branch information
Showing
4 changed files
with
5,474 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
export default async function (key) { | ||
const value = localStorage.getItem(key) | ||
if (!value) return undefined | ||
return JSON.parse(value) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
{ | ||
"name": "storage-tab-sync", | ||
"version": "1.0.0", | ||
"main": "index.js", | ||
"license": "MIT", | ||
"dependencies": { | ||
"next": "9.1.1", | ||
"swr": "link:../.." | ||
}, | ||
"scripts": { | ||
"dev": "next", | ||
"start": "next start", | ||
"build": "next build" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
import storage from '../libs/storage' | ||
|
||
import useSWR, { mutate } from 'swr' | ||
|
||
export default () => { | ||
const { data = { name: "" } } = useSWR('user-name', storage) | ||
|
||
function handleChange(event) { | ||
localStorage.setItem( | ||
'user-name', | ||
JSON.stringify({ name: event.target.value }) | ||
) | ||
mutate('user-name', { name: event.target.value }) | ||
} | ||
|
||
return <div style={{ textAlign: 'center' }}> | ||
<label htmlFor="name">Name</label> | ||
<input id="name" name="name" type="text" value={data.name} onChange={handleChange} /> | ||
</div> | ||
} |
Oops, something went wrong.