'React Native WebSocket onmessage Firing After Re-rendering
I'm encountering a really weird issue with react native and websockets. I'm using a functional component, assigning the websocket to useRef, and there are a few other react hooks as well. When the view loads the websocket is loaded and works just fine. The messages come in just fine as well.
However when I call a hook unrelated to the websocket, the websocket's "onmessage" gets called.
const Home = ({ navigation }) => {
const store = useStore(); // from mobx store using React.useContext
const [riders, setRiders] = useState(store.schedule.riders);
const wss = useRef(null);
useEffect(() => {
const driverId = store.authentication.user.driver;
wss.current = new WebSocket(url);
wss.current.onopen = () => console.log('ws opened');
wss.current.onclose = (e) => console.log('ws closed', e.code, e.reason);
wss.current.onmessage = (e) => {
console.log('onmessage');
};
return () => {
wss.current.close();
};
}, []);
const handleStatusPress = () => {
// AFTER THIS EXECUTES "onmessage" GETS CALLED
store.schedule.updateStatus(ride.id, 'completed');
};
return (
<View>
{riders.map((s) => {
return (
<Animated.View
key={s.id}
style={{ ...styles.riderCard }}
>
<View style={styles.column}>
<Text style={styles.riderName}>{s.name}</Text>
<Text style={styles.riderType}>PICKUP</Text>
<Text style={styles.riderTime}>{moment(parseInt(s.datetime, 10)).format('h:mm A')}</Text>
</View>
<TouchableOpacity
style={styles.bubble}
onPress={() => {
handleStatusPress(s);
}}
>
<Text style={styles.riderStatus}>{s.status}</Text>
</TouchableOpacity>
</Animated.View>
);
})}
</View>
);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
