Home > Software design >  how to use prevstate to localstorage in typescript(react)
how to use prevstate to localstorage in typescript(react)

Time:05-10


type allergyProps = {
  filterAllergy: allergyArray[];
  setRemoveAllergy: Dispatch<SetStateAction<string>>;
  setSearchAllergy: Dispatch<SetStateAction<string>>;
};

type allergyArray = {
  id: number;
  name: string;
};

const Allergy = ({ setSearchAllergy, filterAllergy }: allergyProps) => {
  const [isInput, setIsInput] = useState(false);
  const [removeAllergy, setRemoveAllergy] = useState<string[]>([]);
  const handleInput = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.value) {
      setIsInput(true);
    } else {
      setIsInput(false);
    }
    setSearchAllergy(e.target.value);
  };
  const click = (e: React.MouseEvent<HTMLButtonElement>) => {
    let value = e.currentTarget.name;
    setRemoveAllergy([...removeAllergy, value]);
    localStorage.setItem("allergy", removeAllergy); << #####error point !#######
  };

error name is Argument of type 'string[]' is not assignable to parameter of type 'string'.

   29 |     let value = e.currentTarget.name;
   30 |     setRemoveAllergy([...removeAllergy, value]);
 > 31 |     localStorage.setItem("allergy", removeAllergy);
      |                                     ^^^^^^^^^^^^^
   32 |   };

i want use to prevState for setItem,, how to use prevState of array type?

CodePudding user response:

localStorage cannot hold any data type except for strings. If you would still like to force it, you can convert the array into a string and then place it in localStorage as follows:

localStorage.setItem("allergy", JSON.stringify(removeAllergy));

When you want to read from localStorage, you would need to do this to get it back into the form of an array:

JSON.parse(localStorage.getItem("allergy"));
  • Related