Hexycode
Hexycode

Reputation: 458

Using localStorage in React

Novice in React.

I have a DropDown field with 2 input areas with text and number properties. After I setup the data it stored them in the list order. Check the below screen shot ADABTC 400 (2020-7-30 7:25:15)

enter image description here

After I refresh page this string disappears. How can I store it so that it will stay after page is refreshed? Is there any better alternatives in React to store data instead of localStorage?

CODE

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

const assets = [
  "ADABTC",
  "AIONBTC",
  "ALGOBTC",
  "ARDRBTC",
  "KAVABTC",
  "ETHBTC",
  "ETCBTC"
];

export default function App() {
  const [queries, setQueries] = useState([]);
  const [symbol, setSymbol] = useState("");
  const [price, setPrice] = useState("");
  const [dropdown, setDropdown] = useState([]);

  const onChangeSymbol = e => {
    setSymbol(e.target.value);
  };

  const onChangePrice = e => {
    setPrice(e.target.value);
  };

  var today = new Date();
  var date =
    today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + today.getDate();
  var time =
    today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
  var dateTime = date + " " + time;

  const onClick = () => {
    if (symbol !== "" && price !== "") {
      setQueries(queries => {
        return [
          ...queries,
          `${symbol}` + " " + `${price}` + " " + "(" + dateTime+")"
        ];
      });
      setSymbol("");
      setPrice("");
    }
  };

  useEffect(() => {
    if (symbol !== "" && symbol !== assets.find(rec => rec === symbol)) {
      setDropdown(assets.filter(rec => rec.indexOf(symbol) > -1));
    } else {
      setDropdown([]);
    }
  }, [symbol]);

  return (
    <div id="DropDownArea" className="DropDownField">
      <div id="PriceAlertHistory">
        <h6>Price Alert History</h6>
      </div>
      <ul>
        {queries.map(query => (
          <li>{query}</li>
        ))}
      </ul>
      <input
        type="text"
        placeholder="Symbol"
        value={symbol}
        onChange={onChangeSymbol}
      />
      <input
        type="number"
        placeholder="Price"
        value={price}
        onChange={onChangePrice}
      />
      <button type="submit" onClick={onClick}>
        Set
      </button>
      <ul>
        {dropdown.length !== 0
          ? dropdown.map(asset => {
              return (
                <li
                  onClick={() => {
                    setSymbol(asset);
                    setDropdown([]);
                  }}
                >
                  {asset}
                </li>
              );
            })
          : false}
      </ul>
    </div>
  );
}

Upvotes: 1

Views: 163

Answers (3)

shayanmalinda
shayanmalinda

Reputation: 2267

If you have a Backend save your data into your database and then read those data when page reloads. You can do this inside componentDidMount() method.

Or else if you don't have a Backend then you can store your data in localStorage, sessionStorage or as Cookies . There are some differences between those 3 methods. Choose the one which suits you requirement.

Upvotes: 0

AlexAV-dev
AlexAV-dev

Reputation: 1175

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

const assets = [
  "ADABTC",
  "AIONBTC",
  "ALGOBTC",
  "ARDRBTC",
  "KAVABTC",
  "ETHBTC",
  "ETCBTC"
];

export default function App() {
  const [queries, setQueries] = useState(
    JSON.parse(localStorage.getItem("queries")) || []
  );
  const [symbol, setSymbol] = useState("");
  const [price, setPrice] = useState("");
  const [dropdown, setDropdown] = useState([]);

  const onChangeSymbol = e => {
    setSymbol(e.target.value);
  };

  const onChangePrice = e => {
    setPrice(e.target.value);
  };

  var today = new Date();
  var date =
    today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + today.getDate();
  var time =
    today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
  var dateTime = date + " " + time;

  const onClick = () => {
    if (symbol !== "" && price !== "") {
      setQueries(queries => {
        const query =
          `${symbol}` + " " + `${price}` + " " + "(" + dateTime + ")";
        localStorage.setItem(
          "queries",
          `[${[...queries, query].map(rec => `"${rec}"`)}]`
        );
        return [...queries, query];
      });
      setSymbol("");
      setPrice("");
    }
  };

  useEffect(() => {
    if (symbol !== "" && symbol !== assets.find(rec => rec === symbol)) {
      setDropdown(assets.filter(rec => rec.indexOf(symbol) > -1));
    } else {
      setDropdown([]);
    }
  }, [symbol]);

  return (
    <div id="DropDownArea" className="DropDownField">
      <div id="PriceAlertHistory">
        <h6>Price Alert History</h6>
      </div>
      <ul>
        {queries.map(query => (
          <li>{query}</li>
        ))}
      </ul>
      <input
        type="text"
        placeholder="Symbol"
        value={symbol}
        onChange={onChangeSymbol}
      />
      <input
        type="number"
        placeholder="Price"
        value={price}
        onChange={onChangePrice}
      />
      <button type="submit" onClick={onClick}>
        Set
      </button>
      <ul>
        {dropdown.length !== 0
          ? dropdown.map(asset => {
              return (
                <li
                  onClick={() => {
                    setSymbol(asset);
                    setDropdown([]);
                  }}
                >
                  {asset}
                </li>
              );
            })
          : false}
      </ul>
    </div>
  );
}

Upvotes: 1

Andy Refuerzo
Andy Refuerzo

Reputation: 3332

queries is populated only in onClick(). So when you refresh the page, it gets reinitialized. LocalStorage would work since data is persisted until the browser cache is cleared by the user manually or until the data is cleared by your app.

This shows a good guide to use local storage in react, among other things.

Upvotes: 0

Related Questions