Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot update during an existing state transition in stateless component

I have the following warning :

Warning: setState(...): Cannot update during an existing state transition (such as within render or another component's constructor).

with React-redux-router that I understand, but do not know how to fix.

This is the component that is generating the warning.

const Lobby = props => {
  console.log("props", props)
  if (!props.currentGame)
    return (
      <div>
        <input type="text" ref={input => (roomName = input)} />
        <button
          className="button"
          onClick={() => {
            props.createRoom(roomName.value)
          }}
        >
          Create a room
        </button>
      </div>
    )
  else
    return (
      <div>
        {props.history.push(`/${props.currentGame}[${props.username}]`)}
      </div>
    )
}

export default Lobby

What I'm doing here is that my component receives the currentGame property from the Redux store. This property is initialized as null. When the user creates a game, I want to redirect him on a new URL generated by the server that I assign inside the property currentGame with a socket.io action event that is already listening when the container of the component Lobby is initialized.

However, since the currentGame property changes, the component is re-rendered, and therefore the line

{props.history.push(`/${props.currentGame}[${props.username}]`)}

generates a warning since the property currentGame now has a value, and the history property should not get modified during the re-render.

Any idea on how to fix it ?

Thanks!

like image 241
sulo Avatar asked Mar 20 '18 12:03

sulo


2 Answers

You should not write props.history.push in render, instead use Redirect

const Lobby = props => {
  console.log("props", props)
  if (!props.currentGame)
    return (
      <div>
        <input type="text" ref={input => (roomName = input)} />
        <button
          className="button"
          onClick={() => {
            props.createRoom(roomName.value)
          }}
        >
          Create a room
        </button>
      </div>
    )
  else
    return (
      <div>
        <Redirect to={`/${props.currentGame}[${props.username}]`} />
      </div>
    )
}
like image 89
Shubham Khatri Avatar answered Oct 25 '22 23:10

Shubham Khatri


Do one thing, instead of writing the condition and pushing with history.push(), just put the code inside componentDidMount() if you are trying to do in the beginning.

componentDidMount(){
 if(condition){
   history.push('/my-url');
 }
}
like image 42
Baraja Swargiary Avatar answered Oct 25 '22 21:10

Baraja Swargiary