Search code examples
ruby-on-railsreactjsaxiosrails-api

axios PUT request to rails-API


I'm trying to post a new score instance to my rails-API but whenever I submit it the app resets itself without updating the state - the console isn't returning an error but it's not rendering the json either - so many things could be wrong but does anyone have an idea of where I should start looking.

my ScoreForm.js

export default class ScoreForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      strokes: null,
      selectedCourse: null,
    };

  }

  selectCourse(){
    console.log(this.refs.courseSelector.value);
    this.setState( {selectedCourse: this.refs.courseSelector.value} );
  }

  enterStrokes(){
    console.log(this.refs.typeStrokes.value);
    this.setState({strokes: this.refs.typeStrokes.value});
  }

  handleSubmit = () => {
    const score = { strokes:this.state.strokes, user_id: this.props.currentUser, course_id: this.state.selectCourse}
    axios.put(
      `http://localhost:3001/api/v1/scores`, {score: score})
    .then(response => {
      console.log(response);
      this.props.updateScores(response.data)
    })
    .catch(error => console.log(error))
  }

  render() {
    var courseOptions = (this.props.courseList.map((course) => {
      return <option key={course.id} value={course.id}>{course.name}</option> ;
    }));
    return (
      <form onSubmit={this.handleSubmit}>
        <input ref='typeStrokes' onChange={(e) => {this.enterStrokes(); } } />
        <select ref='courseSelector' onChange={(e) => { this.selectCourse(); } }>{courseOptions}</select>
      </form>
    );
  }
}

my rails routes.rb

Rails.application.routes.draw do
  namespace :api do
    namespace :v1 do
      get 'users/scores' => 'scores#index'
      get 'users/:id/scores' => 'users#scores'
      resources :users
      resources :scores
      resources :courses
    end
  end

end

my scores_controller.rb

module Api::V1
  class ScoresController < ApplicationController
    before_action :set_course

    def index
      @scores = Score.order("created_at DESC")
      render json: @scores
    end

    def create
      differential = (params[:score][:strokes].to_i) - @course.rating

      @score = Score.create(score_params.merge(:differential => differential))
      render json: @score
    end

    private

    def set_course
      @course = Course.find(params[:course_id])
    end

    def score_params
      params.require(:score).permit(:user_id, :course_id, :strokes)
    end

  end
end

Solution

  • If you run rails routes or rake routes (depending on your rails version) you will see what routes those resources defined in your routes.rb are creating. PUT requests get mapped into the update method in your controller, so you need to define it to update your resources and return the JSON response you're expecting in your React app.