Create hook useLocalStorage for NextJs
This is a library that provides an easy way to manage localStorage, having the possibility to connect changes through different components.
- Installing
- Import
- Use
- Use in multiple components
- Developer
- Repositories
Using npm:
``bash`
npm i uselocalstoragenextjs
`javascript`
import { useLocalStorage } from "uselocalstoragenextjs";
`javascript`
const {
value, //Value of element in localStorage
setLocalStorage, //function for modify localStorage
load, //if the value has been loaded or not
} = useLocalStorage({
name: "cart", //name of element in localStorage
defaultValue: [], //defaulValue if element in localStorage if null
parse: (v: any) => {
//function for modify value after get of localStorage
return JSON.parse(v == "" ? "[]" : v);
},
updateValue(oldValue, newValue) {
//function for modify value before set of localStorage
return [...oldValue, newValue];
},
});
`javascript
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 (
export default Home;
`
`javascript
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
{value.length}
>
)}
>
);
};
`
`ts``
//interface of value
interface notification_interface {
type?: "ok" | "error" | "warning";
msg?: string;
}
const {
value, //Value of element in localStorage
setLocalStorage, //function for modify localStorage
load, //if the value has been loaded or not
} = useLocalStorage
name: "notification", //name of element in localStorage
defaultValue: {}, //defaulValue if element in localStorage if null
parse: (v: any) => {
//function for modify value after get of localStorage
return JSON.parse(v == "" ? "{}" : v);
},
});
Email blancofrancisco34@gmail.com
- Github