1

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>
  );
}
2
  • 2
    It's pretty common to persist app state to local storage. Have you tried that and have an issue? or just looking for suggestions? Commented Jul 30, 2020 at 6:38
  • I think you have 3 options to persist data: localStorage/sessionStorage/cookie, url, or backend (database). Commented Jul 30, 2020 at 6:43

3 Answers 3

1
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>
  );
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.