Skip to content
Advertisement

Submit a form to Rails backend with ReactJS

It is my first time working with ReactJS in a Rails solution and the task is an emergency request that doesn’t give me enough time to learn React before taking up the sprint to work on. The Backend is a JSON (API) solution and I have been able to write a ReactJS to render the GET endpoint to list the Tasks in the database. However, when I got to the point of submitting a form with ReactJS for a POST endpoint, nothing happened. My inputs do not save into the Database and the form did not disappear to the Task list endpoint. I do not know what I am doing wrong. However, below is code snippets to my solution.

controller/api/v1/tasks_controller.rb

JavaScript

config/route.rb

JavaScript

model/task.rb

JavaScript

views/homepage/index.htnl.erb

This is empty file

views/layout/application.html.erb

JavaScript

app/javascript/components/App.jsx

JavaScript

app/javascript/components/NewTask.jsx

JavaScript

app/javascript/packs/Index.jsx

JavaScript

app/javascript/routes/Index.jsx

JavaScript

When I call the API Endpoints on Postman and Insomnia, they function as expected. But when I submit inputs from ReactJS Form (i.e. NewTask.jsx), nothing saves into the database.

What am I doing wrong. I do hope somebody can help me through this.

Advertisement

Answer

Apparently, the problem lies in the onSubmit event method because it targets the avatar_url instead of form inputs attributes called name. So this is what I used to make it work.

  1. Changed the onChange event to be:

    JavaScript
  2. Correct the Form Input Attributes, to be:

    JavaScript
Advertisement