Created
August 13, 2021 06:52
-
-
Save sonnylazuardi/4f67e58b8da48584ecd682e9accdca58 to your computer and use it in GitHub Desktop.
Astro React Vue. Global State Management: Zustand
This file contains hidden or 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
import React from "react"; | |
import { useStore } from "./store"; | |
export default function CounterReact({ demo }) { | |
const state = useStore((state) => state); | |
let add = () => { | |
state.inc(); | |
}; | |
let subtract = () => { | |
state.dec(); | |
}; | |
return ( | |
<div> | |
React Count: {state.count} {demo} | |
<br /> | |
<button onClick={subtract}>-</button> | |
<button onClick={add}>+</button> | |
</div> | |
); | |
} |
This file contains hidden or 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
<template> | |
<div>Vue Count: {{ count }} {{ demo }}</div> | |
<button @click="subtract">-</button> | |
<button @click="add">+</button> | |
</template> | |
<script> | |
import { useStore } from "./store"; | |
const Counter = { | |
name: "CounterVue", | |
props: { | |
demo: String, | |
}, | |
data() { | |
return { | |
count: useStore.getState().count, | |
}; | |
}, | |
mounted() { | |
this.unsub = useStore.subscribe( | |
(value) => (this.count = value), | |
(state) => state.count | |
); | |
}, | |
beforeUnmount() { | |
if (this.unsub) this.unsub(); | |
}, | |
methods: { | |
add() { | |
useStore.getState().inc(); | |
}, | |
subtract() { | |
useStore.getState().dec(); | |
}, | |
}, | |
}; | |
export default Counter; | |
</script> | |
<style scoped></style> |
This file contains hidden or 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
import create from "zustand"; | |
export const useStore = create((set) => ({ | |
count: 20, | |
inc: () => set((state) => ({ count: state.count + 1 })), | |
dec: () => set((state) => ({ count: state.count - 1 })), | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment