user10328862
user10328862

Reputation: 155

React State is not updated with socket.io

When page loaded first time, I need to get all information, that is why I am calling a fetch request and set results into State [singleCall function doing that work] Along with that, I am connecting websocket using socket.io and listening to two events (odds_insert_one_two, odds_update_one_two), When I got notify event, I have to check with previous state and modify some content and update the state without calling again fetch request. But that previous state is still [] (Initial). How to get that updated state?

Snipptes

  const [leagues, setLeagues] = useState([]);
  
  const singleCall = (page = 1, params=null) => {

    let path = `${apiPath.getLeaguesMatches}`;
    Helper.getData({path, page, params, session}).then(response => {
      if(response) {
        setLeagues(response.results);
      } else {
        toast("Something went wrong, please try again");
      }
    }).catch(err => {
      console.log(err); 
    })
  };

  const updateData = (record) => {

    for(const data of record) {
      var {matchId, pivotType, rateOver, rateUnder, rateEqual} = data;
      const old_leagues = [...leagues]; // [] becuase of initial state value, that is not updated
      const obj_index = old_leagues.findIndex(x => x.match_id == matchId);
      if(obj_index > -1) {
        old_leagues[obj_index] = { ...old_leagues[obj_index], pivotType, rateOver: rateOver, rateUnder:rateUnder, rateEqual:rateEqual};
        setLeagues(old_leagues);
      }
    }
  } 

  useEffect(() => {

    singleCall();

    var socket = io.connect('http://localhost:3001', {transports: ['websocket']});

    socket.on('connect', () => {
        console.log('socket connected:', socket.connected);
    });
    socket.on('odds_insert_one_two', function (record) {
      updateData(record);
    });

    socket.on('odds_update_one_two', function (record) {
      updateData(record);
    });

    socket.emit('get_odds_one_two');

    socket.on('disconnect', function () {
      console.log('socket disconnected, reconnecting...');
      socket.emit('get_odds_one_two');
    });

    return () => {
        console.log('websocket unmounting!!!!!');
        socket.off();
        socket.disconnect();
    };
  }, []);

Upvotes: 1

Views: 1179

Answers (1)

codemax
codemax

Reputation: 1352

The useEffect hook is created with an empty dependency array so that it only gets called once, at the initialization stage. Therefore, if league state is updated, its value will never be visible in the updateData() func.

What you can do is assign the league value to a ref, and create a new hook, which will be updated each time.

const leaguesRef = React.useRef(leagues);

React.useEffect(() => {
  leaguesRef.current = leagues;
});

Update leagues to leaguesRef.current instead.

  const updateData = (record) => {
    for(const data of record) {
      var {matchId, pivotType, rateOver, rateUnder, rateEqual} = data;
      const old_leagues = [...leaguesRef.current]; // [] becuase of initial state value, that is not updated
      const obj_index = old_leagues.findIndex(x => x.match_id == matchId);
      if(obj_index > -1) {
        old_leagues[obj_index] = { ...old_leagues[obj_index], pivotType, rateOver: 
  rateOver, rateUnder:rateUnder, rateEqual:rateEqual};
        setLeagues(old_leagues);
      }
    }
  } 

Upvotes: 1

Related Questions