DEV Community

Maylene Poulsen
Maylene Poulsen

Posted on

Basic fetch requests with JS + Rails

An important concept to learn is being able to handle 'GET' and 'POST' requests in an application.

For my Javascript group project at the Flatiron School, we were required to build an app using a Rail API backend and Javascript as the frontend. This was the point where I started to feel like an actual junior developer. There is so much to learn, but it was exciting to build something simple and work on the functionality. For this post I'll use examples from a previous lab that helped students learn how the backend and frontend associated.

The Rails API sets up the basic models and associations as well as the controllers. The frontend (Javascript) will send a fetch request to our backend hosted on

 http://localhost:3000/trainers


and return json data to use on our web page. The json is usually returned as an array of objects.

An example fetch request might look like this:
From the frontend in our index.js file

function fetchTrainers() {
  return fetch(TRAINERS_URL)
    .then(response => response.json())
};

This returns a promise that we can use after the DOM has loaded.

document.addEventListener('DOMContentLoaded', () => {
  fetchTrainers()
    .then(results => console.log(results));
});

These objects were returned because the data was accessed from the trainers controller.

  def index 
    trainers = Trainer.all
    render json: trainers, only: [:id, :name], include: :pokemons
  end

Next we would use the returned data to render the objects on our page. These functions could be written in our index.js file

The above 'GET' request starts in our frontend javascript file => is sent to the controller => the controller accesses our database and returns the data we wanted sending it back to the frontend => and finally the frontend can use the returned data

An example fetch request to post or save information in our database might look similar to this:

From our front end, we might gather data from inputs or objects on the page. Then we will pass this data along to a controller on the backend through out fetch request. This data is sent as a json object that we include in the fetch.

function addANewPokemon(event) {
  const trainerId = event.target.dataset.trainerId;
  data = { trainer_id: trainerId}

  fetch(POKEMONS_URL, {
    method: 'POST',
    headers:  {
      "Content-Type": "application/json",
      "Accept": "application/json"
    },
    body: JSON.stringify(data)
  })
};

This request will be sent to a different controller and the create action.
In the create action we could use data input from either a form that is passed along in the data object to the fetch or in this specific case, the Ruby Faker gem was used to help create a new object to save to the database.

 def create
    pokemon = Pokemon.create(
      nickname: Faker::Name.first_name,
      species: Faker::Games::Pokemon.name,
      trainer: Trainer.find(params[:trainer_id])
    )
    render json: pokemon
  end

Remember create in Rails also saves the object to the database. We can specify on our fetch 'POST' request to have the json object returned if we want to use the data immediately.

.then(response => response.json())
.then(result => console.log(result))

In summary, the fetch request is directed to a specific URL that is associated with a controller. The method inside the request lets the controller know what action to send the request to. For example, 'GET' can either go to the index or the show if the URL passed in has an :id associated with it. The 'POST' request is sent to the create action. A 'PATCH' request is sent to update and 'DELETE' request is sent to the destroy action in the controller.

Top comments (2)

Collapse
 
sumnerdavid profile image
David Sumner

This honestly makes so much sense. Been confused as to how this would work but you laid it in a way that it makes sense to a newbie like me!

Collapse
 
reythedev profile image
Rey van den Berg

This had just what I needed! I hadn't touched this stuff in a while and your short, to-the-point article was a perfect reminder. Thanks!