Mike Tallerico
Mike Tallerico

Reputation: 125

Using fetch API to get data from Rails

So I am building a react on rails project to learn some new things. I am trying to use the fetch API to get data from the db.

I have tried this method and this one. But I might be implementing them wrong.

This is my fetch route:

fetch('/get_data')
      .then(response => {
        response.json();
      })
      .then(data => console.log(data));

I have my route set up in Ruby on Rails:

match '/get_data' => 'get_data#pull', via: :get

I have my controller just doing something simple at the moment to see if I can get any data.

class GetDataController < ApplicationController
  def pull
    @allproduct = Product.all
    render json: @allproduct
  end
end

Thanks for any help in pointing me in the right direction!

Upvotes: 1

Views: 2500

Answers (1)

Mike Tallerico
Mike Tallerico

Reputation: 125

The issue was that I needed a return statement in my fetch call. :)

fetch('/get_data')
      .then(response => {
        return response.json();
      })
      .then(data => console.log(data));

Upvotes: 4

Related Questions