I m working on an app in which I have FlatList and which contains list of cards. I have survey cards and when user perform any survey I add response of that survey in local DB and updated FlatList. My FlatList got updated but when card got rendered all the local data updated expect the values those I am firstly storing in local state and then show while rendering card.
For example:
I want to update title of my card on button press
- I am adding my card title in local useState because I need that value in future
so, I declared like :
const [title, setTitle] = useState('');
Now I want to update item.title on button click:
let newArray = [...feedArray]; const index = newArray.findIndex(object => { return object.cardId === item.cardId; }); newArray[index].title = "I am checking issue for survey not updated" setFeedArray([...newArray]);
also, My useEffect is like:
useEffect(() => {
setTitle(item.title)
},[]}
My setFeedArray list got updated but my card not updated with latest title as I am storing value in local store. If I don't use local state and directly show item.title then it got updated but I want to store my value in setTitle and show from there.
What is the issue. Please help.
CodePudding user response:
try this :
const handleButtonClick = () => {
let newArray = [...feedArray];
const index = newArray.findIndex(object => {
return object.cardId === item.cardId;
});
newArray[index].title = "I am checking issue for survey not updated";
setFeedArray([...newArray]);
setTitle(newArray[index].title);
}
It looks like the issue you are facing is related to the way you are updating the title in your FlatList. The problem is that you are using a local state variable (title) to store and display the title of your card, but you are not updating this variable when the title changes.
CodePudding user response:
You can use a dependency array for rerendering.
useEffect(() => {
setTitle(item.title)
},[title]}