Episodes

Resources

Download Source Code

Summary

# app/javascript/components/HelloWorld.js
import React from "react"
import PropTypes from "prop-types"
import User from './User.js'
import UserForm from './UserForm.js'

class HelloWorld extends React.Component {
  constructor(props, context){
    super(props, context)

    this.state = {
      users: this.props.users,
      first_name: '',
      last_name: ''
    }
  }

  handleUserInput = (obj) => {
    this.setState(obj)
  }

  handleFormSubmit = () => {
    var user = { first_name: this.state.first_name, last_name: this.state.last_name }
    // {user: { first_name: value, last_name: value}}
    fetch('/users', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      mode: 'same-origin',
      body: JSON.stringify({ user: user })
    }).then(function(response){
      return response.json()
    }).then(function(j){
      this.addNewUser(j)
    }.bind(this))
  }

  addNewUser = (user) => {
    var users = this.state.users.concat([user]).sort(function(a,b) {
      return new Date(b.created_at) - new Date(a.created_at)
    })
    this.setState({ users: users })
  }

  render () {

    return (
      <div>
        { this.state.users.map(function(user){
          return (
            <User key={user.id} user={user} />
          );
        })}
        <UserForm key='UserForm' 
          onUserInput={this.handleUserInput}
          onFormSubmit={this.handleFormSubmit}
        />
      </div>
    );
  }
}

export default HelloWorld

# app/javascript/components/UserForm.js
import React from "react"
import PropTypes from "prop-types"
class UserForm extends React.Component {
  handleChange = (e) => {
    var name = e.target.name
    var object = {}
    object[name] = e.target.value
    this.props.onUserInput(object)
  }

  handleSubmit = (e) => {
    e.preventDefault()
    this.props.onFormSubmit()
  }

  render () {
    return <form onSubmit={this.handleSubmit}>
      <h1>Make new user</h1>
        <input name="first_name" placeholder="First Name" onChange={this.handleChange} />
        <input name="last_name" placeholder="Last Name" onChange={this.handleChange}  />
        <input type='Submit' value='Save User' readOnly/>
      </form>;
  }
}

export default UserForm

# users_controller.rb
class UsersController < ApplicationController
  skip_before_action :verify_authenticity_token
  def create
    user = User.new(user_params)
    if user.save
      render json: user
    else
      render json: user.errors, status: :unprocessible_entry
    end
  end

  private

  def user_params
    params.require(:user).permit(:first_name, :last_name)
  end
end

# welcome_controller.rb
class WelcomeController < ApplicationController
  def index
    @users = User.all.order(created_at: :desc)
  end
end

# routes.rb
Rails.application.routes.draw do
  resources :users, only: :create
  root 'welcome#index'
end