Skip to content

Commit

Permalink
Add local state sharing example
Browse files Browse the repository at this point in the history
  • Loading branch information
afc163 committed Nov 5, 2019
1 parent a2d700b commit 0407034
Show file tree
Hide file tree
Showing 4 changed files with 5,509 additions and 0 deletions.
3 changes: 3 additions & 0 deletions examples/local-state-sharing/libs/store.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const initialStore = { name: "john" };

export default initialStore;
15 changes: 15 additions & 0 deletions examples/local-state-sharing/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "local-state-sharing",
"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"
}
}
52 changes: 52 additions & 0 deletions examples/local-state-sharing/pages/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { useState } from "react"
import initialStore from "../libs/store"
import useSWR, { mutate } from "swr"

function Profile() {
const { data } = useSWR("globalState", () => Promise.resolve(initialStore))
const [value, updateValue] = useState((data || {}).name)
if (!data) {
return null
}
return (
<div>
<h1>My name is {data.name}.</h1>
<input
value={value}
onChange={e => updateValue(e.target.value)}
style={{ width: 200, marginRight: 8 }}
/>
<button
type="primary"
onClick={() => {
mutate("globalState", { ...data, name: value })
}}
>
Uppercase my name!
</button>
</div>
)
}

function Other() {
const { data } = useSWR("globalState", () => Promise.resolve(initialStore))
if (!data) {
return null
}
return (
<div style={{ border: "1px solid #ddd", marginTop: 30, padding: 20 }}>
<h1>
Another Component: <br />
My name is {data.name}.
</h1>
</div>
)
}

export default () => (
<div style={{ padding: 40 }}>
useSWR can share state bettween components:
<Profile />
<Other />
</div>
)
Loading

0 comments on commit 0407034

Please sign in to comment.