I have a problem in making app with react native.
I use useState, but its value is not updated and the component is not re-rendered.
This is my code.
import React, {useEffect, useState} from 'react';
import {View, Text, TouchableOpacity, Image, StyleSheet} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
function MyScreen({route}) {
var dateString = route.params;
const [JsonValue, setJsonValue] = useState([]);
const readData = async (day) => {
//Code to load data from AsyncStorage
//get [{character: "A", bool: false}]
const ReadValue = await AsyncStorage.getItem(dateString);
const data = ReadValue != null ? JSON.parse(ReadValue) : null;
setJsonValue(data);
}
useEffect(() => {
readData(dateString);
}, [JsonValue])
return(
<View>
{JsonValue.map((_item, key) => (
<View key={key}>
<TouchableOpacity onPress={() => {
var loopvar = 0;
for (const itemitem of JsonValue) {
if (itemitem.character = _item.character) {
var item = JSON.parse(JSON.stringify(itemitem));
item.bool = false;
var itemall = JSON.parse(JSON.stringify(JsonValue));
itemall[loopvar] = item;
setJsonValue(itemall);
break;
}
loopvar += 1;
}
}}>
<Image
source={require('./assets/checkbox.png')}
/>
</TouchableOpacity>
</View>
))}
</View>
);
}
The problem comes from setJsonValue(itemall);
After the code runs, it doesn’t render and the values ββdon’t change.
Before running setJsonValue(itemall);
, the value of JsonValue was [{character: "A", bool: false}] and the value of itemall was [{character: "A", bool: true}].
Can you solve this problem? If so, please give me an answer.
Thank you.
2
Answers
In your code the
item
you are using in if statement is conflicting with the scopeditem
inside the if block and hence item will always beundefined
and henceitem.character
will throw error. Also as you mentioned in your question that you want thebool
to betrue
initemall
but in your code you are setting it tofalse
which won’t change the apparent value ofJsonValue
because it was alreadyfalse
but state will update though.Here try with below code, it is working for me. State is updating and re-render is also working.
Happy coding π
The issue you are facing may be because of the quality comparison operator
itemitem.character = __item.character
To compare the values you should use the triple equal sign
===
operator or double equals sign==
So it will be
if (itemitem.character === __item.character)
Let me know if this works π