React State is not updated with socket.io

半腔热情 提交于 2021-02-11 12:40:29

问题


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

回答1:


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);
      }
    }
  } 


来源:https://stackoverflow.com/questions/63370656/react-state-is-not-updated-with-socket-io

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!