Skip to content

Instantly share code, notes, and snippets.

@sonnylazuardi
Created August 13, 2021 06:52
Show Gist options
  • Save sonnylazuardi/4f67e58b8da48584ecd682e9accdca58 to your computer and use it in GitHub Desktop.
Save sonnylazuardi/4f67e58b8da48584ecd682e9accdca58 to your computer and use it in GitHub Desktop.
Astro React Vue. Global State Management: Zustand
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>
);
}
<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>
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