Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add example sharing local state between components #76

Merged
merged 2 commits into from
Nov 9, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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="button"
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 between components:
<Profile />
<Other />
</div>
)