-1

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.

image of problem

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.

Edit

this 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.

Rahul
  • 1,858
  • 1
  • 12
  • 33
  • Probably wouldn't include your API token in publicly posted code... – Matt Dec 07 '20 at 10:37
  • 2
    @Matt i had removed about 10 to 12 characters of `API`, so, i don't this can create any issue. – Rahul Dec 07 '20 at 10:41
  • "In my case, the state is not updated even, I wait for an hour." – that doesn't make any sense. Of course it's updated, you're just not printing it anywhere when it updates. – Guy Incognito Dec 07 '20 at 10:54
  • @GuyIncognito `not printing it anywhere` i am printing it on console, see `console.log(markerPos.longitude,data['gps.lon'])` – Rahul Dec 07 '20 at 10:58
  • Yes. You're printing it *before it has updated*. You're not printing it *after* it has updated. – Guy Incognito Dec 07 '20 at 10:59
  • @GuyIncognito thanks for your time and effort, it worked by using the correct marked answer. – Rahul Dec 07 '20 at 12:20

1 Answers1

1

The state of markerPos is updated asynchronously. Try rendering MarkerPos and you should see it changing. If you want to call function when it changes, use another useEffect hook

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:
        "xxxxxxx",
    },
  });

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)
        })
    },[])

    useEffect(()=>{
       console.log(markerPos)
    },[markerPos])
    return null;
}
Jkarttunen
  • 6,764
  • 4
  • 27
  • 29
  • Here, we are listing change `markerPos`,i don't this will work. But, i am trying this. – Rahul Dec 07 '20 at 10:55
  • In your component, the Route component is not rerendering, because props are not chaning, so there is no need to update the markerPos state, since it is not used – Jkarttunen Dec 07 '20 at 10:59