RABEYA KHATUN MUNA
RABEYA KHATUN MUNA

Reputation: 47

How can I refresh all the cookies, token and session after logout calling API using Rails Hotwire

I am working on a project which is done in Rails Hotwire where devise gem has been used for authentication and, in frontend Stimulus.js has been used. Instead of using link_to , I want to write an API with delete method, to refresh like: cookies, token , cause time delay is taking some time to remove all which is creating an issue:

My initial Code:

<%= link_to '/api/v2/iam/users/sign_out', method: :delete, data: { action: 'click->biz-account#logout' } do %>
  <button class="hidden lg:block btn--outlined py-[16px]" data-cy="logout"><%= I18n.t('biz.log_out') %></button>
<% end %>

biz-account.js

logout() {
setTimeout(() => {
  location.href = '/'
 }, 300);
}

Now, I want to call the delete API from the view part, done the whole delete thing in javascript api. How to do this?

I tried to do this, which is not working:

app/javascript/services/api_calls.js

export const logout = 
  function () {
  call(
   '/api/v2/iam/users/sign_out',
  {},
  function (value) {
    if (value.message) {
      window.alert = 
       openSnackbar(value.message, 'success')
    } else {
       window.alert = 
        openSnackbar(value.errors, 'error')
    }
    callback(value);
  },
  {verb: 'DELETE'})
}

Upvotes: 0

Views: 447

Answers (1)

yungindigo
yungindigo

Reputation: 281

If you want to do it with javascript you could use the Fetch API to make the request and then wait for the response and check if it was successful or not.

If you wanted to use no javascript instead of using a link you could switch to using a button than it would redirect to wherever the backend points it.

Also if you are using hotwire you change the method: option on the link to use the hotwire method then it will follow the redirect from the backend

link_to "api", method: :delete  # With rails UJS
link_to "api", data: { turbo_method: :delete } # With hotwire

Upvotes: 0

Related Questions