sbak
sbak

Reputation: 63

Use fetch to pass variable in rails

I am creating an app in Rails with Reactjs. I want to pass the value of input field to the controller as a variable so that I can use that variable in def create. How can I do that with fetch?

Upvotes: 1

Views: 893

Answers (1)

a.fahmiin
a.fahmiin

Reputation: 400

Use fetch's POST request to your API backend endpoint of your :create method. Make sure that you include your variables in a params payload when POSTing.

Then in your controller, you can access your variables through params

EDIT:

From the fetch api docs example in using POST (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)

async function postData(url = '', data = {}) {
  const response = await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  });
  return response.json();
}

postData('/your/api/endpoint', { data: 'yourData' }).then(res=> { console.log(res) });

Then in your controller, access { data: 'yourData' } through params like so:

def create
  @data = params[:data]
  // Do what you want with @data here
end

It's also best to whitelist your params first before using them in your controller.

Upvotes: 2

Related Questions