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 :: js remove first character from string 
Javascript :: import and export type in js 
Javascript :: js foreach key value 
Javascript :: javascript ascii character 
Javascript :: cors axios 
Javascript :: on hover display block jquery 
Javascript :: get yyyy-mm-dd hh:mm from date javascript 
Javascript :: elapsed time function() {math javascript 
Javascript :: change url with javascript without reloading 
Javascript :: javascript last character of a string 
Javascript :: AngularJS how to use btn-group or radio group in list 
Javascript :: how to print in java script 
Javascript :: event.propagation not working 
Javascript :: this.setstate is not a function in react native 
Javascript :: react big calendar messages 
Javascript :: javascript trim whitespace 
Javascript :: momentjs docs 
Javascript :: javascript close app phonegap 
Javascript :: async storage react native 
Javascript :: json comment 
Javascript :: is javascript faster than python 
Javascript :: how to create an element in js using the map method 
Javascript :: react recoil 
Javascript :: line break in js 
Javascript :: upload image postman 
Javascript :: confluent kafka nodejs 
Javascript :: window.location.origin 
Javascript :: JavaScript then() method 
Javascript :: upload file to database with axios and formData 
Javascript :: getrecord lwc 
ADD CONTENT
Topic
Content
Source link
Name
3+7 =