Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

use localStorage hook

import { useCallback, useEffect, useState } from "react";

export const useLocalStorage = (key, initialValue) => {
  const initialize = (key) => {
    try {
      const item = localStorage.getItem(key);
      if (item && item !== "undefined") {
        return JSON.parse(item);
      }

      localStorage.setItem(key, JSON.stringify(initialValue));
      return initialValue;
    } catch {
      return initialValue;
    }
  };

  const [state, setState] = useState(null); // problem is here

  // solution is here....
  useEffect(()=>{
    setState(initialize(key));
  },[]);

  const setValue = useCallback(
    (value) => {
      try {
        const valueToStore = value instanceof Function ? value(storedValue) : value;
        setState(valueToStore);
        localStorage.setItem(key, JSON.stringify(valueToStore));
      } catch (error) {
        console.log(error);
      }
    },
    [key, setState]
  );

  const remove = useCallback(() => {
    try {
      localStorage.removeItem(key);
    } catch {
      console.log(error);
    }
  }, [key]);

  return [state, setValue, remove];
};
Comment

use localstorage react hook

  const [name, setName] = useLocalStorage("name", "Bob");
Comment

PREVIOUS NEXT
Code Example
Javascript :: ejemplo async await javascript 
Javascript :: .yarnrc.yml get node module back 
Javascript :: create new project angular 
Javascript :: read files in javascript 
Javascript :: webpack dev server 
Javascript :: summernote mentions ajax 
Javascript :: how to make data toggle=modal always active 
Javascript :: algolia docs react instant search 
Javascript :: array.length 
Javascript :: react useeffect hooks 
Javascript :: angular 7 selected 
Javascript :: how to use mdbreact in react js 
Javascript :: alert in javascript 
Javascript :: sorting an array based on certain element 
Javascript :: create div with js 
Javascript :: coreui react change background color 
Javascript :: redirect all routes to main component vue 
Javascript :: useref array 
Javascript :: get all a tags javascript 
Javascript :: adding event listener to multiple elements 
Javascript :: debug javascript in chrome 
Javascript :: print stuff in console javascript 
Javascript :: js parameter vs argument 
Javascript :: jquery is not defined error in wordpress 
Javascript :: jquery parse url parameters 
Javascript :: parallax using npm parallax 
Javascript :: how to get the current username with wscript 
Javascript :: how to start react project on atom 
Javascript :: how to append a data to list in redux 
Javascript :: js round to x decimal places 
ADD CONTENT
Topic
Content
Source link
Name
9+9 =