dynamitetech
dynamitetech

Reputation: 9

How do i make my counter value remain, when i refresh the page with localStorage in react

i have tried all i could, i could get a solution, i need my count value to remain, even if i refresh my page. for example if my count is up to 3, and when i refresh my browser, the 3 should remain and not start from zero.

can i get any help?? i am currently learning localstorage

here is the code

import React, { useState } from "react";

export default function LocalStorageSetting() {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    setCount((prevCount) => prevCount + 1);
  };

  localStorage.setItem("count", count);

  return (
    <div>
      <button onClick={handleClick}>Increase</button>
      <h1>{count}</h1>
    </div>
  );
}

Upvotes: -1

Views: 868

Answers (3)

drethedevjs
drethedevjs

Reputation: 484

@epascarello's answer works. You could also use the setCount function you created.

const storageCount = Number(localStorage.getItem("count")) ?? 0;
const [count, setCount] = useState(storageCount);

Also note that localStorage stores string key/value pairs. count should have something like .toString() on the end when adding it as the value. So use localStorage.setItem("count", count.toString()).

Upvotes: 0

Guilherme Moraes
Guilherme Moraes

Reputation: 149

You can start your state using the value stored in Local Storage, this way, the value count will init by LS value. Keep in mind that Local Storage saves your value as string, so you need to parse the value before init to be sure that your value will be typed as Number

const [count, setCount] = useState(Number(localStorage.count || 0));

Something I like to do it keep the value save in the save function that changed the value, keeping the value changes in a single function.

const handleClick = () => {
  setCount((prevCount) => prevCount + 1);
  localStorage.setItem("count", count);
};

Upvotes: 0

epascarello
epascarello

Reputation: 207527

Read it when you set the initial value

const [count, setCount] = useState(+(localStorage.count || 0));

Upvotes: 1

Related Questions