#local storage fetching

22 messages · Page 1 of 1 (latest)

winter nova
#

Hello guys! I am trying to store my counter (which counts the no. of attempts ) in my local storage, it is storing in local storage but when i try to fetch in (val variable) it shows null value for that i am not able to figure out why it is happening....
const [counter,setcounter] =React.useState(0);

  React.useEffect(() => {
        const allHeld = dice.every(die => die.isHeld)
        const firstValue = dice[0].value
        const allSameValue = dice.every(die => die.value === firstValue)
        if (allHeld && allSameValue) {
            setTenzies(true)
            var itemSet = (window.localStorage.getItem('tenzies_max') === null);
            if(itemSet){
                window.localStorage.setItem('tenzies_max',`${counter}`);
            }
            else{
                if(window.localStorage.getItem('tenzies_game')>`${counter}`)
                window.localStorage.setItem('tenzies_game',`${counter}`);
            }
            var val=window.localStorage.getItem('tenzies_game');
                console.log(val)
        }
    }, [dice])
snow nebula
#

if you do this window.localStorage.getItem('tenzies_max') return null?

#

I can only detect problem is this line js if(window.localStorage.getItem('tenzies_game')>`${counter}`) you are comparing string value (the result of localStorage.getItem()) to a number value (counter) using the greater than operator (>).

#

This can lead to unexpected results, as string comparison works differently than numeric comparison.

#

To fix this you have to convert the localStorage value to number using parseInt() or parseFloat()

winter nova
sweet aspen
#

@winter nova would you be able to share a repo with us?
It would be useful to see more of your code

winter nova
snow nebula
#

where are you setting "tenzies_game"? its value never stored in the localstorage, and you are trying to get that value which were not exist in localstorage. localstorage only storing the "tenzies_max" nothing else.

#

I don't understand what you are trying to do here or what feature you are adding, I cannot guess what is "tenzies_game" here.

#

What I think you probably have typo error here, you want to set and get tenzies_max but may be you type or want get tenzies_game which were never stored in local storage.

#
React.useEffect(() => {
    const allHeld = dice.every((die) => die.isHeld);
    const firstValue = dice[0].value;
    const allSameValue = dice.every((die) => die.value === firstValue);
    if (allHeld && allSameValue) {
      setTenzies(true);
      var itemSet = window.localStorage.getItem("tenzies_max") === null;
      if (itemSet) {
        window.localStorage.setItem("tenzies_max", `${counter}`);
      } else {
        if (parseInt(window.localStorage.getItem("tenzies_max")) > counter)    // changed
          window.localStorage.setItem("tenzies_max", `${counter}`);            // changed
      }
      var val = window.localStorage.getItem("tenzies_max");                    // changed
      console.log(val);
    }
  }, [dice]);
#

This will store the lowest tenzies roll in localstorage. and I think this you want to do, if not then i don't know...

winter nova
snow nebula
#

are you understanding what I'm saying? sorry if you don't understand my english, it is not my first language.

winter nova
sweet aspen
#

@winter nova you almost got it right!
I believe the problem is caused by not parsing the data correctly and you also missed counter from the dependency list which could also cause problems in our case.

Here is a working solution:
||```js
React.useEffect(() => {
const allHeld = dice.every((die) => die.isHeld);
const firstValue = dice[0].value;
const allSameValue = dice.every((die) => die.value === firstValue);

if (allHeld && allSameValue) {
  setTenzies(true);

  try {
    // This is a stringified value
    const localStorageValue = window.localStorage.getItem("tenzies_max");
    if (localStorageValue != null) {
      // This is the parsed value (in our case is an integer) as we already guarded against null or undefined
      const parsedValue = JSON.parse(localStorageValue);
      // If the parsed value is greater than the new one
      if (parsedValue > counter) {
        // We always want to encode/stringify the value using JSON.stringify()
        const stringifiedValue = JSON.stringify(counter);
        // Store the stringified value
        window.localStorage.setItem("tenzies_max", stringifiedValue);
      }
    } else {
      // We always want to encode/stringify the value using JSON.stringify()
      const stringifiedValue = JSON.stringify(counter);
      // Store the stringified value
      window.localStorage.setItem("tenzies_max", stringifiedValue);
    }
  } catch (error) {
    const errorMsg = error instanceof Error ? error.message : error;
    console.error(errorMsg);
  }
}

}, [counter, dice]);

#

@winter nova let me explain a couple of bits. The previous message did not have enough characters left, sorry.

#
  1. You can only store string values into the localstorage. You should always use JSON.stringify() to encode your values correctly into a string format

  2. When you read localstorage you will get back a string or null value You will need to parse that value so you get back the original type/model of that value. You need yo use JSON.parse() on the returned value from the localstorage.

3.You should always guard against null value before you parse the stringified value and only proceed if the value actually exits.

  1. You should always wrap the parsing code part into try catch to avoid your application to collapse. The value in localstorage can be malformed so you should always code defensively

  2. useEffect dependency list needs to be complete, and you should always consider having a base case within useEffect to guard against invalid code execution.

winter nova
#

wow!! @sweet aspen Thank u man!! Thanks for explaining this.....I learned alot your a great man now its working....