0.2.2 • Published 12 months ago
nes-zustand v0.2.2
N E S - Z U S T A N D
By hau la
This library handles setting the value of the store outside of the React component, an idea inspired by the recoil-nexus library.
To achieve the flexible usage provided by recoil-nexus, I customized it based on the core of zustand, allowing the value to be reset from anywhere.
Installation
npm install nes-zustand
yarn add nes-zustand
Usage
// src/store.ts
import { createNesZustandStore } from "nes-zustand";
// Create a store
export const loadingState = createZustandStore({
key: "loadingState",
default: false,
});
// api.ts
// Function submit form outside of the React component
// This example want to set loading when submitting the api
import { loadingState } from "@/store/common";
import { firebase } from "@/utils/config/firebase";
import { addDoc, collection } from "firebase/firestore";
import { getZustandValue, setZustandValue } from "nes-zustand";
import { toast } from "sonner";
import { IContactValues } from "./type";
export const submitContactAPI = async (payload: IContactValues) => {
setZustandValue(loadingState, true); // set loading value => true
try {
const docRef = await addDoc(collection(firebase, "users"), {
...payload,
});
const loading = getZustandValue(loadingState);
console.log("Get value", loading); // Output => true (You can get value here)
console.log("Document written with ID: ", docRef.id);
} catch (error) {
console.error("Error adding document: ", error);
} finally {
setZustandValue(loadingState, false); // finally set loading value => false
toast("Submit successfully!");
}
};
// Loading component
import { loadingState } from "@/store/common";
import { Backdrop, CircularProgress } from "@mui/material";
import { useStore } from "zustand";
export const MainLoading = () => {
const loading = useStore(loadingState, (state) => state.value);
return (
<Backdrop open={loading}>
<CircularProgress
sx={{
height: "30px !important",
width: "30px !important",
color: "#fff",
}}
/>
</Backdrop>
);
};
Method | Returns |
---|---|
createZustandStore | create state function |
setZustandValue | setter function, pass value to be set as second parameter |
getZustandValue | getter function |
nes-zustand
nes-zustand
0.2.2
12 months ago
0.2.1
1 year ago
0.2.0
1 year ago
0.1.9
1 year ago
0.1.8
1 year ago
0.1.7
1 year ago
0.1.6
1 year ago
0.1.5
1 year ago
0.1.4
1 year ago
0.1.3
1 year ago
0.1.2
1 year ago
0.1.1
1 year ago
0.1.0
1 year ago
0.0.9
1 year ago
0.0.8
1 year ago
0.0.7
1 year ago
0.0.6
1 year ago
0.0.5
1 year ago
0.0.4
1 year ago
0.0.3
1 year ago
0.0.2
1 year ago
0.0.1
1 year ago
1.0.4
1 year ago
1.0.3
1 year ago
1.0.2
1 year ago
1.0.1
1 year ago
1.0.0
1 year ago