DrummerGenius
DrummerGenius

Reputation: 545

Calling a function in a Stimulus Controller from a Rails Helper or Controller?

I am working on a Rails app where I want to use Javascript's navigation API to get me my user's geolocation. I have the code in a controller under 'app/javascript/location_controller' that works.

import { Controller } from "stimulus"

export default class extends Controller {
    connect(){
        this.getUserLocation()
    }

    getUserLocation(){
        if (navigator.geolocation) {
           navigator.geolocation.getCurrentPosition((position) => console.log(position.coords), (error)=> console.log(error));
        } else {
            alert("Could not get your current location! Please allow location services for RiseUp.")
        }
    }
}

How would I go about called 'getUserLocation' from a Rails Helper?

Upvotes: 0

Views: 3524

Answers (1)

rewritten
rewritten

Reputation: 16435

Stimulus controllers, and in general any javascript, is not run by your ruby server, but by the user's browser.

If you want to get a value back from it, you will need to make some ajax call, and get it from a normal rails controller.

Something like:

async getUserLocation() {
  let data = new FormData();
  let position = await navigator.geolocation.getCurrentPosition();
  data.set('position', position);
  await fetch('/api/notify_location', {method: 'POST', body: data, credentials: true});
}

And you have to route it on the backend:

scope 'api' do
  post 'notify_location' => 'location#notify'
end

and get it in a controller

class LocationController < ApplicationController
  def notify
    # do as needed, you will be able to get the session here
    # because the fetch function was passed credentials: true
    # but beware, this request won't match `request.xhr?` because
    # fetch is not XMLHTTPRequest.

Upvotes: 2

Related Questions