Search code examples
javascriptruby-on-railsajaxreactjsreact-rails

react-rails : component does not re-render after record created


As I am following a tutorial, I am trying to get my GamesBox re-render after a new record(game) has been created through an AJAX call.

The record get saved, and I am able to see it by refreshing, however this not seem to be the React way ...

Container :

var GamesBox = React.createClass ({

  getInitialState: function(){
    return {
      game: this.props.games
    }
  },

  parentGameSubmit (formData){

    $.ajax({
      url: "/games",
      dataType: 'json',
      type: 'POST',
      data: formData,

      success: function(games) {

        this.setState({games: games});

      }.bind(this),

      error: function(response, status, err) {

        console.log(this.props.url, status, err.toString())
      }.bind(this)


    });
  },

    render () {
      return (
        <div>
        <h1> Hey everyone </h1>
        
        <Game games={this.state.game} />

        <GameForm parentGameSubmit={this.parentGameSubmit}/>
        </div>
      );
    }
});

Game list rendered :

var Game = React.createClass({

 renderProjectRows: function(){
    return(
      this.props.games.map(function(game){
        return(
          <div className="row" style={{marginTop: "20px"}} key={game.id}>

            <div className="col-sm-2">
              <h2 className="text-center" key={game.id}><a href={"/games/" + game.id}> {game.name} </a></h2>
            </div>

          </div>
        )
      })
    );
  },

  render: function() {
    return(
      <div>

        <div className="row" style={{marginTop: "50px"}}>

          <div className="col-sm-2">
          </div>

          <div className="col-sm-2" style={{fontWeight: "bold"}}>
            Name
          </div>

        </div>

        {this.renderProjectRows()}

      </div>
    );
  }

});

Form :

var GameForm = React.createClass({

  getInitialState: function(){
    return {name: ""};
  },

  resetState: function(){
    this.setState({name: ""});
  },

  newGameSubmit: function(e){
    e.preventDefault();

   this.props.parentGameSubmit({game: {name: this.state.name, white_castling: this.state.white_castling, black_castling: this.state.black_castling}},
    this.resetState);
   this.setState({name: ''});
  },

  handleNameChange: function(e){
    this.setState({name: e.target.value});
  },


  renderGameNameField: function(){


    return(

      <div className='row'>

        <div className='col-sm-4'>

          <div className= 'form-group'>

            <input
              name="game[name]"
              type="string"
              placeholder="Game name"
              value={this.state.name}
              onChange={this.handleNameChange}
              className="string form-control"
            />

          </div>

        </div>

      </div>
    );
  },



  render: function() {

    return(
      <div>
        <h4 style={{marginTop: "50px"}}> Create New Game </h4>

        <form style={{marginTop: "30px"}} onSubmit={this.newGameSubmit}>

          <div className='form-inputs'/>


            {this.renderGameNameField()}
            


            <div className='row'>
              <div className='col-sm-4'>
                <input type="submit" value="Save" className='btn btn-primary' />
              </div>
            </div>

        </form>

      </div>

    );
  }
});

Game controller :

class GamesController < ApplicationController
  before_action :authenticate_user!

  def index
    @game = Game.all
  end

  def new
    @game = Game.new
  end

  def create
    @game = Game.new(game_params)
     respond_to do |format|
    if @game.save
      @game.update(white_user_id: current_user[:id])
      format.html { redirect_to @game, notice: 'Project was successfully created.' }

      format.json { render json: Game.all.order(:name)}
    else
      format.html {render :new}
    end
  end
  end
                                             
   private

  def game_params
    params.require(:game).permit(:name, :white_castling, :black_castling)
    end
  end
     

Please hit me with insights


Solution

    1. You are constantly interchanging between game and games. i.e game: this.props.games in your GameBox component. You should uses games if it's an array which it is in that case. (I am assuming this is true because you are using a map function on it in your Game component).
    2. You are updating the games state when a successful ajax is sent and not the game state which you are actually using.

    If you want a super quick fix you can just change this.setState({games: games}); to this.setState({game: games}); in your parentGameSubmit function.