I am trying to create an authentication component on with React on the FE and Rails BE.
I'm not sure what's the issue here, when i send a request to the API to create the user. the password is not permitted and the application breaks.
My Signup action on the FE:
export const signupUser = createAsyncThunk('user/signupUser',
async(userData, thunkAPI) => {
console.log('userData',userData)
let url = 'http://localhost:3000/users';
let apiObject = {
method:'POST',
headers: {
accept: "application/json",
"content-type":"application/json"
},
body: JSON.stringify({
user_name: userData.name,
email: userData.email,
password: userData.password,
password_confirmation: userData.password_confirmation
})
}
fetch(url, apiObject)
.then(response => response.json())
.then(data => console.log(data))
}
)
My User Model on the BE:
class User < ApplicationRecord
has_secure_password
validates :user_name, presence: true
validates :email, uniqueness: true, presence: true
# has_many :reports dependent: :destroy
# has_many :properties dependent: :destroy
end
user/controller on the BE:
class UsersController < ApplicationController
def index
users = User.all
render json: users
end
def create
user = User.new(user_params)
binding.pry
if user.save && user.authenticate(user_params[:password])
binding.pry
token = encode_token({user_id: user.id})
render json: { user: UserSerializer.new(user).serializable_hash, token: token}, status: :created
else
render json: {error: user.errors.full_messages.to_sentence}, status: :unprocessable_entity
end
end
private
def user_params
params.require(:user).permit(:user_name, :email, :password, :password_confirmation)
end
end
I used pry to try to understand so here's the flow: UI- signup enter image description here
and this is the breakpoint when the params can't pass the passwords. enter image description here
Can anyone help with this ?
The controller expects the payload in the following structure as defined by:
params.require(:user).permit(:user_name, :email, :password, :password_confirmation)In your SignUp action, pass the payload accordingly:
For further reading, refer here.