4

I've setItem in Home.js file as:

    AsyncStorage.setItem('myValue', JSON.stringify(3))

Now in another file called Ask.js I've a button where I'm calling it:

    const [val, setVal] = useState("1");
...
            <TouchableOpacity onPress={() => {
                AsyncStorage.getItem("myValue").then((value) => {
                    setVal(value)
                    console.log(value + ' and ' + val)
                });
            }}>

Based on the console.log When this button is pressed it logs 1 and 3 which seems like the value is not updated but if I press it again it'll print 3 and 3 which means the useState value was updated but it didn't rerender.

So how do I re-render?

Chaudhry Talha
  • 7,231
  • 11
  • 67
  • 116

2 Answers2

0

The problem is : you are not using setVal to update the value. It should be like this.

 <TouchableOpacity onPress={() => {
                AsyncStorage.getItem("myValue").then((value) => {
                    setVal(value)
                    console.log(value + ' and ' + val)
                });
            }}>
sakshya73
  • 5,570
  • 5
  • 22
  • 41
0

I tried to replicate your example. I created this sandbox in react-native. For me is working fine.

EDIT 1:

When this button is pressed it logs 1 and 3 which seems like the value is not updated

That's because of the asynchronous nature of state hook (see this question). It is normal.

You didn't post the code in which you expect to see the change of val, I guess the problem is there.

Zeno Dalla Valle
  • 957
  • 5
  • 16