0

I'm trying to make a search bar, where the search will occur once the button (or enter) is clicked. To this, I want to save the searched phrases in localStorage.

I have no problem with the first part. Things work fine when searching with a button or on enter-click. However, when I try to add the search as an array to localStorage I keep getting issues (like string doesn't work with an array, and many more. I've tried A LOT of different things). I've done this with JS and vanilla React, but never with TS.

In the provided code, the search works, and to put in at least something (as simple as I could) - the latest value is also stored in localStorage.

The code can be found here

Or here:

// index file
import { useState } from "react";
import { Searchbar } from "./searchbar";
import { SearchContainer } from "./style";

export const Search = () => {
  const [search, setSearch] = useState<string>("");

  return (
    <SearchContainer>
      <Searchbar setSearch={setSearch} />
      <p>SEARCHED: {search}</p>
    </SearchContainer>
  );
};
// search bar file
import { useRef, KeyboardEvent, useEffect } from "react";

type SearchProps = {
  setSearch: React.Dispatch<React.SetStateAction<string>>;
};

export const Searchbar = ({ setSearch }: SearchProps) => {
  // with useRef we don't have to reload the page for every input
  const inputRef = useRef<HTMLInputElement>(null);

  const handleClick = () => {
    setSearch(String(inputRef.current?.value));
    localStorage.setItem("form", JSON.stringify(inputRef.current?.value)); // Issue here
  };

  // Enable search with the enter-key
  const log = (e: KeyboardEvent): void => {
    e.key === "Enter" ? handleClick() : null;
  };

  useEffect(() => {
    const value = localStorage.getItem("form");
    value ? JSON.parse(value) : "";
  }, [setSearch]);

  return (
    <div>
      <input
        type="text"
        autoComplete="off"
        ref={inputRef}
        placeholder="search game..."
        onKeyDown={log}
      />
      <button onClick={handleClick}>SEARCH</button>
    </div>
  );
};

I've been on this for a while now so any help is appreciated. (I am also trying to learn TS from scratch, but until I get to here...).

Battleaxe
  • 64
  • 1
  • 7
  • 1
    The `value` of an `HTMLInputElement` is always a string. There is no need to stringify a string (nor a need to call `String()` on a `value`). There is no difference between how you do it in JavaScript vs. TypeScript except for the types you give values. I'm not sure why you want to add the value to local storage, but there's no mystery to adding a string to local storage. It's unclear what you mean by "as an array". Do you want to keep a history of the search terms? – Heretic Monkey Jan 02 '23 at 19:26
  • Thanks. Well, since I want to store more than one value in localStorage I thought an array might be good. So what I'm trying to do is let you make a search "one" -> store that "one" in localStorage, and when you make your next search "two" -> we will have both "one" and "two" in our localStorage. In an array :) – Battleaxe Jan 02 '23 at 19:34
  • If you want to keep an array, then you need to add the current search term to the existing array (if present) and store the new array, serialized. – Heretic Monkey Jan 02 '23 at 19:43
  • Yeah, I'm getting that. I just feel so stupid atm – Battleaxe Jan 02 '23 at 19:48
  • Does this answer your question? [How do I store an array in localStorage?](https://stackoverflow.com/questions/3357553/how-do-i-store-an-array-in-localstorage) – Heretic Monkey Jan 02 '23 at 19:51
  • Haha, I just found the same (and I thought I'd searched everywhere). I will have a look. Currently, my code won't run at all - only 'loading', haha. Thank you very much. – Battleaxe Jan 02 '23 at 19:54

0 Answers0