Home > front end >  React Native : update useState() Value
React Native : update useState() Value

Time:09-22

I am trying to update setStars value. even when the condition is true is not updating. I do not know why

const [Stars, setStars] = useState(0);
if (passedData === 'part 1' && CurrentQuestion === QuestionData.length - 1) {
  if (score >= 1 && score <= 2) {
    setStars(10);
    alert(Stars);
    let PartOne = JSON.stringify(Stars);
    AsyncStorage.setItem('Part1', PartOne);
  }
  if (score >= 3 && score <= 4) {
    setStars(20);
    let PartOne = JSON.stringify(Stars);
    AsyncStorage.setItem('Part1', PartOne);
  }
}

CodePudding user response:

After setting Stars value (setStars(10)) don't use alert to print the change .Alert will not print the immediately changed values. Instead try console.log(Stars) after the if condition. You will see the changes.

const [Stars, setStars] = useState(0);
if (passedData === 'part 1' && CurrentQuestion === QuestionData.length - 1) {
  if (score >= 1 && score <= 2) {
    setStars(10);

    let PartOne = JSON.stringify(Stars);
    AsyncStorage.setItem('Part1', PartOne);
  }
  if (score >= 3 && score <= 4) {
    setStars(20);
    let PartOne = JSON.stringify(Stars);
    AsyncStorage.setItem('Part1', PartOne);
  }
}
console.log(Stars);

CodePudding user response:

The issue is that setStars is an asynchronous function i.e. the code below it will keep executing when there is no guarantee that the value of Stars has changed yet.

To do what you want you can either hold the value you are setting it to in a variable:

const newStarValue = 10
setStars(newStarValue);

let PartOne = JSON.stringify(newStarValue);
AsyncStorage.setItem('Part1', PartOne);

Or (much better) use a useEffect hook to see the value after the setStars has completed:

useEffect(() => {
    let PartOne = JSON.stringify(Stars);
    AsyncStorage.setItem('Part1', PartOne);
}, [Stars]);

The uesEffect hook is much more robust as it will run whenever the Stars value is changed

  • Related