1

I am trying to build a React front end on top of a Rails API and I am currently working on the registration form on React. Below is my attempt at handling the form submission.

 const handleSubmit = (evt) => {
    evt.preventDefault()
    fetch(`http://localhost:3001/users`, {
      method: "POST",
      headers: {
        "Accept": "application/json"
      },
      body: JSON.parse(JSON.stringify({
        email,
        password,
        first_name,
        last_name,
        phone_number
      }))
    })
      .then(resp => console.log(resp.json))

    setFirst("")
    setLast("")
    setEmail("")
    setPassword("")
    setPhone("")
  }

However, when I print out the params received from React, it is empty. Below is my Rails User create method.

def create
            @user = User.new(user_params)
            puts user_params
        if @user.save
                render json: @user.id, status: :created
                UserMailer.welcome_email(@user).deliver_now
            else
                render json: {errors: @user.errors.full_messages}, status: :unprocessable_entity
            end
        end

        def destroy
            @user.destroy
        end

I checked here and here and a bunch of other places but they say pretty much the same thing. Wrap the body in JSON.stringify or JSON.parse or both. But it isn't working for me.

1 Answer 1

1

use axios and qs stringifier:

npm i axios qs 

then:

import axios from "axios";
import qs from "qs";

axios.post(url,qs.stringify(your body))
Sign up to request clarification or add additional context in comments.

4 Comments

So I should scrap the entire fetch?
yep axios is commonly used with react, easy to implement and understand.
Is there a reason why my method wasn't working? I was kinda following a tutorial.
did you try JSON.stringify only without JSON.parse

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.