1

I am currently running a Rails 6 API backend and using React for my front end (separately, I am not using react-rails). I am using devise and google_oauth2 for my authentication. My auth flow works just fine, I can login with Google Sign-in and redirect to my home page, and now I am trying to render some data.

I'd like to get the current_user (provided by devise) data to render in React, but my requests are returning null for the JSON response. I set up a separate current_user_controller that I am using as the endpoint for the fetch, which looks like this:

class CurrentUserController < ApplicationController
    before_action :authenticate_user!
    def index
        if user_signed_in?
            render json: current_user
            puts current_user
            puts user_signed_in?
        else
            render json: {}, status: 401
            puts user_signed_in?
        end
    end
end

The rails server shows my puts statements and they return the current_user instance and true, respectively, so I know it is running as it should. When I go to localhost:3000/current_user directly in the browser, the complete JSON shows up with first/last name, email, token, etc... but the fetch request from my front-end returns null for the data, it looks like this:

componentDidMount = () => {
        this.fetchUser()
    }

    fetchUser = () => {
        console.log('fetching user')
        return fetch(userAPI)
            .then(res => res.json())
            .then(data => {
                console.log('setting user state')
                console.log(data)
                this.setState({ user: data })
            })
    }

I can get a valid data response with the above code at the /users endpoint if I swap it out in the userAPI const, so I don't think there's anything up with the request. I tried rendering current_user from my users controller in the same way as my custom controller, and I got the same null response.

I also tried the solution here and installed the devise-token-authentication gem, but STILL get null. I hope I explained everything clearly, if I did not, please let me know. I really appreciate any help on this, I've been googling for hours and can't seem to find anything.

0 Answers0