How to redirect from React front-end with Rails routes?

Viewed 982

I am new to React and struggling to redirect after making a post request to my api.

In an erb view, I am using a javascript pack tag to render some React components on a new resource page. I am using a button onClick to send my post request (axios) to api/v1/resources. I'd like to redirect to admin/resources after the request is sent.

  1. I am wondering why redirecting from the create action in my Api::V1::ResourcesController doesn't work.

  2. Can I redirect without setting up react router? If not, how can I set that up? (All of my routes are defined in Rails).

Everything I can find seems to pertain to an entire React front-end when I am only using bits of React in a predominantly Rails front-end.

This is my handleSubmit function that gets called onClick:

const handleSubmit = () => {
    let newResourceParams = {
      title: title,
      description: description,
      occurred_on: occurredOn,
      resource_type: resourceType
    }
    Api.postNewResource(newResourceParams)
  }

Here is Api.postNewResource:

postNewResource(data) {
    return AxiosApi.post('/api/v1/resources', data)
      .then(({data}) => data['data'])
      .catch((errors) =>
        console.log(errors)
      )
  }

And here is my create action in Api::V1::ResourcesController:

def create
  Resource.create(resource_params)
  redirect_to admin_resources_path
end

Any guidance or help on this would be greatly appreciated. Thanks

1 Answers

You could try something like this:

redirect_to admin_resources_path, format: :json

Let me know if any luck with that?

Source

P.S. Very well formulated question. ;)

Related