'Screen not re-rendering even when the state is changed and screen is focused
I am using useFocused from react-navigation to check when screen is focused.
If it is focused then fetch the latest conversations and set New state of conversations.
All of this is working perfectly but newly fetched conversations are not rendering on screen and old conversations are being rendered. (I am sure there is a change in conversation and state is updated because I have checked it thoroughly)
I just don't understand why screen is not re-rendering when state is changed.
Following is the code for understanding:
const Chats = ({ navigation, route }) => {
const [User, setUser] = useUser();
const [conversations, setConversations] = React.useState([]);
const focused = useIsFocused();
React.useEffect(() => {
if (focused) {
console.log("triggered");
fetchConvos();
}
return () => {};
}, [focused]);
const fetchConvos = () => {
fetch(IpAddress + User.userid + "/conversations", {
method: "GET",
headers: {
"Content-Type": "application/json",
},
redirect: "follow",
referrerPolicy: "no-referrer",
})
.then((res) => res.json())
.then((received) => {
setConversations([...received]);
});
};
return (
<View style={styles.container}>
<Header name={"Chats"} />
<ScrollView style={styles.messageView}>
{conversations.map((val) => {
return (
<ChatComponent
conversation_name={val?.conversation_name}
last_message={val.last_message}
message_type={val.message_type}
/>
);
})}
</ScrollView>
</View>
);
};
Solution 1:[1]
You overwrite your previous data when the fetch is resolved. You should include the previous data when updating the state.
setConversations((conversations) => [...conversations, ...received]);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tomas Vancoillie |
