diff --git a/examples/local-state-sharing/libs/store.js b/examples/local-state-sharing/libs/store.js new file mode 100644 index 000000000..344662cbb --- /dev/null +++ b/examples/local-state-sharing/libs/store.js @@ -0,0 +1,3 @@ +const initialStore = { name: "john" }; + +export default initialStore; diff --git a/examples/local-state-sharing/package.json b/examples/local-state-sharing/package.json new file mode 100644 index 000000000..3584ad4ac --- /dev/null +++ b/examples/local-state-sharing/package.json @@ -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" + } +} diff --git a/examples/local-state-sharing/pages/index.js b/examples/local-state-sharing/pages/index.js new file mode 100644 index 000000000..966016fcf --- /dev/null +++ b/examples/local-state-sharing/pages/index.js @@ -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 ( +
+

My name is {data.name}.

+ updateValue(e.target.value)} + style={{ width: 200, marginRight: 8 }} + /> + +
+ ) +} + +function Other() { + const { data } = useSWR("globalState", () => Promise.resolve(initialStore)) + if (!data) { + return null + } + return ( +
+

+ Another Component:
+ My name is {data.name}. +

+
+ ) +} + +export default () => ( +
+ useSWR can share state between components: + + +
+)