Skip to content

Commit

Permalink
Add example using SWR to sync storage between tabs (#74)
Browse files Browse the repository at this point in the history
  • Loading branch information
sergiodxa authored and shuding committed Nov 4, 2019
1 parent 457abf9 commit 9ae313d
Show file tree
Hide file tree
Showing 4 changed files with 5,474 additions and 0 deletions.
5 changes: 5 additions & 0 deletions examples/storage-tab-sync/libs/storage.js
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)
}
15 changes: 15 additions & 0 deletions examples/storage-tab-sync/package.json
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"
}
}
20 changes: 20 additions & 0 deletions examples/storage-tab-sync/pages/index.js
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>
}

0 comments on commit 9ae313d

Please sign in to comment.