简体   繁体   中英

Updating React Component state Dynamically based on server state

I have a component that shows no of players logged in as soon as the component loads.

function PlayerList({gamePin}){
const [playerList, setPlayerList] = useState("");
useEffect( ()=>{
    axios.get("http://localhost:8080/game/lobby/"+gamePin)
         .then( response =>{
             setPlayerList(response.data)
         })
})
return(
    <div className='container'>
        <div className='lobbycontainer'>
            <h1>Lobby</h1>
            <Grid container spacing={3}>
                {playerList.map(player=>{
                    <Player {PlayerName,PlayerId} />
                })}
            </Grid>
        </div>
    </div>
    )}

export default PlayerList;

This will display the name of the player who is logged in and any other players already logged into the lobby.

But my question is how do the players who are already logged in will get to know about the new players who joined.

Possible Approach

  1. Send a request with a time interval of every 2 seconds.

    setInterval(httpRequest,2000);

Is this the right way to do this? are there any alternate approaches?

How does a component dynamically update its state based on the changes in the backend? and respond to the changes by rerendering the component to reflect the changes.

That is pretty close. Use a "componentDidMount" useEffect hook patter, ie provide an empty dependency array ( [] ). Refactor the GET request into a callback function invoked on an interval and don't forget to return an effect cleanup function to clear the interval when this component unmounts.

useEffect(() => {
  const timerId = setInterval(() => {
    axios.get("http://localhost:8080/game/lobby/" + gamePin)
      .then(response => setPlayerList(response.data))
  }, 2000);

  return () => clearInterval(timerId);
}, []);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM