Skip to content

Method called twice in html_load controller #2095

@thewebartisan7

Description

@thewebartisan7

** Describe the bug **
In the html_load controller the method turbo() is called twice.
Here https://github.com/orchidsoftware/platform/blob/master/resources/js/controllers/html_load_controller.js#L10
and here https://github.com/orchidsoftware/platform/blob/master/resources/js/controllers/html_load_controller.js#L20

The same about csrf() method, since turbo:load is fired also in first page load, it's called here:
https://github.com/orchidsoftware/platform/blob/master/resources/js/controllers/html_load_controller.js#L19
and here: https://github.com/orchidsoftware/platform/blob/master/resources/js/controllers/html_load_controller.js#L28

** Suggested change **

By just removing method connect(), it should works fine, because in initialize method is called turbo() which call also csrf() via turbo:load event.

import ApplicationController from "./application_controller";
import axios from 'axios';

export default class extends ApplicationController {
    /**
     *
     */
    initialize() {
        this.axios();
        this.turbo();
    }

    /**
     * Initialization & configuration Turbo
     */
    turbo() {
        document.addEventListener("turbo:load", () => {
            this.csrf();
        });
    }

    /**
     * Creating an instance Axios
     */
    axios() {
        window.axios = axios;
    }

    /**
     * We'll load the axios HTTP library which allows us to easily issue requests
     * to our Laravel back-end. This library automatically handles sending the
     * CSRF token as a header based on the value of the "XSRF" token cookie.
     */
    csrf() {
        const token = document.head.querySelector('meta[name="csrf_token"]');

        if (!token) {
            return;
        }

        /**
         * Next we will register the CSRF Token as a common header with Axios so that
         * all outgoing HTTP requests automatically have it attached. This is just
         * a simple convenience so we don't have to attach every token manually.
         */
        window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
        window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

        document.addEventListener("turbo:before-fetch-request", (event) => {
            event.detail.fetchOptions.headers["X-CSRF-TOKEN"] = token.content;
        });

    }

    /**
     *
     */
    goToTop() {
        window.scrollTo({top: 0, behavior: 'smooth'});
    }
}

Before submitting PR, can you please tell me if I am missing something?
After a quick test it work fine also with above changes.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions