useLocalStorage
This is a library that provides an easy way to manage localStorage, having the possibility to connect changes through different components.
Installing
Using npm:
npm i uselocalstoragenextjs
Import
import { useLocalStorage } from "uselocalstoragenextjs";
Use
const {
value,
setLocalStorage,
load,
} = useLocalStorage({
name: "cart",
defaultValue: [],
parse: (v: any) => {
return JSON.parse(v == "" ? "[]" : v);
},
updateValue(oldValue, newValue) {
return [...oldValue, newValue];
},
});
Use in multiple components
import { useLocalStorage } from "uselocalstoragenextjs";
import Component from "./component";
const Home = () => {
const { value, setLocalStorage, load } = useLocalStorage({
name: "cart",
defaultValue: [],
parse: (v: any) => {
return JSON.parse(v == "" ? "[]" : v);
},
updateValue(olValue, newValue) {
return [...olValue, newValue];
},
});
return (
<div>
Cart
<div>{JSON.stringify(value)}</div>
<br />
<button
onClick={() => {
setLocalStorage({ p: 1 });
}}
>
Add New Product
</button>
<Component />
</div>
);
};
export default Home;
import { useLocalStorage } from "uselocalstoragenextjs";
export default () => {
const { value, load } = useLocalStorage({
name: "cart",
defaultValue: [],
parse: (v: any) => {
return JSON.parse(v == "" ? "[]" : v);
},
});
return (
<>
{load && (
<>
N Items in Cart
<br />
{value.length}
</>
)}
</>
);
};
Use typescript
interface notification_interface {
type?: "ok" | "error" | "warning";
msg?: string;
}
const {
value,
setLocalStorage,
load,
} = useLocalStorage<notification_interface>({
name: "notification",
defaultValue: {},
parse: (v: any) => {
return JSON.parse(v == "" ? "{}" : v);
},
});
Developer
Francisco Blanco
Github franciscoblancojn
Email blancofrancisco34@gmail.com
Repositories