I have a component like below.
import React,{useEffect,useState} from "react";
import {Marker} from "react-map-gl";
import io from "socket.io-client";
import { BASE_URL } from "../../../config/urls";
const socket = io(BASE_URL, {
query: {
token:
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXV",
},
});
export default function Route(){
const [markerPos, setMarkerPos] = useState({
longitude:8.5455940,latitude:47.3977421
})
const update=(data)=>{
const obj = {
longitude:data['gps.lon'],
latitude:data['gps.lat']
}
setMarkerPos(prevProps =>{
return {...prevProps,longitude:obj.longitude,latitude:obj.latitude}
});
console.log(markerPos.longitude,data['gps.lon'])
}
useEffect(()=>{
socket.on("mission_data",(socketData)=>{
update(socketData)
})
},[])
return null;
}
When visited some of the questions on StackOverflow, i came to this solution.
Questions:Why is my state not being updated using React Hooks?
React State is not updated with socket.io
React Hooks: state not updating when called inside Socket.io handler
React State is not updated with socket.io
socket.on
is being called only once.
Although, socketData
always gets updated. Every time new data is coming from socket.io
.
You can see in the image above, right side data which is red colored is coming from the socket and it is updating. But, the left side data which is green colored is the react state variable is not updating.
Editthis question is not a duplicate of useState set method not reflecting change immediately.
I know react asynchronously update state. So, the state update will not reflect immediately.
In my case, the state is not updated even, I wait for an hour.