1

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!

7
  • First thing I note here is that you are missing pull action at line fetch('/get_data/pull') Commented Sep 25, 2018 at 9:26
  • That shouldn't be necessary with the given route. Commented Sep 25, 2018 at 9:32
  • What actually happens in your browser when you run this code? Anything in the console or network tab that might give you a clue? Commented Sep 25, 2018 at 9:32
  • 1
    Oh! Return the result of response.json() from your first then, you're console logging nothing because there is nothing returned for the next call in the promise chain Commented Sep 25, 2018 at 9:52
  • 1
    No problem! Please add an answer with your solution and accept it :-) Commented Sep 25, 2018 at 9:55

1 Answer 1

4

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.