1

I'm trying to update my state when onLongPress triggered.
I'm printing the result right after the setState but it shows nothing (on the first press) Code:

const [pressedImagesm setPressedImages] = useState([]);
...
onLongPress={() => {
          setPressedImages(oldArray => [...oldArray, { [index]: true }]);
          console.log(pressedImages);
}}
Odium
  • 87
  • 8
  • Does this answer your question? [React, state setter not updating the value](https://stackoverflow.com/questions/71004802/react-state-not-getting-updated-when-calling-the-related-setstate) – Youssouf Oumar Aug 12 '22 at 16:10

2 Answers2

3

That's because setPressedImages does not update the state object (pressedImages) directly. Instead, it adds this update to a queue, and the updated state is reflected on the next render of your component.

This is a pretty common React question - there's a lot of helpful content out there that explains it in more detail (such as this article or this SO question).

Donut
  • 110,061
  • 20
  • 134
  • 146
0

try this:

const [pressedImages, setPressedImages] = useState([]);
...
onLongPress={() => {
   const cloneArray = [...pressedImages];
   cloneArray.push({ [index]: true });
   setPressedImages(cloneArray);
}}

console.log('Updated pressedImages:', pressedImages);
Chaurasia
  • 494
  • 1
  • 6
  • 22