Preventing Unauthorized Access: Redirecting to Login Page in Vue.js

Here is the code snippet I'm working with:

<script>
    export default{
        props:['idStore'],
        methods:{
            addFavoriteStore(event){
                $(function () {
                    $(document).ajaxError(function (e, xhr, settings) {
                        if (xhr.status == 401) {
                            window.Laravel.baseUrl+'/login'
                        }
                        else {
                            event.target.disabled = true
                            const payload= {id_store: this.idStore}
                            this.$store.dispatch('addFavoriteStore', payload)

                            setTimeout(function () {
                                location.reload(true)
                            }, 1500)
                        }
                    });
                });
            }
        }
    }
</script>

When the favorite button is clicked, it triggers the addFavoriteStore method.

After running the addFavoriteStore method, a condition is supposed to check if the user is unauthorized. However, despite trying this conditional statement, it does not seem to work as expected. No errors are showing up in the console either.

Why might the condition be failing to work properly?

Answer №1

Hey @moses-toh, I'm thrilled that my suggestions were helpful for you :-).

As you were working with Laravel and using Blade syntax, you can utilize Blade/PHP to determine if the user is logged in or not, and display the relevant Button/Message. Your implementation looks great:

   @if (Auth::user())
     <favorite-button>&heart; Favorite</favorite-button>
   @else
     <a href="{{route('login')}}">Login To Favorite</a>
   @endif

I hope this solution meets your needs.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Integrating Project Tango with Ionic and/or Angular in a cutting-edge mobile application

I'm currently working on a mobile app project and I could use some advice. The majority of the app can be developed using angular.js (and possibly ionic) JavaScript technology. However, there is one aspect that requires integration with an API, specif ...

Continuously decrease a sequence of identical numbers in an array through recursion

One of the key challenges was to condense an array of numbers (with consecutive duplicates) by combining neighboring duplicates: const sumClones = (numbers) => { if (Array.isArray(numbers)) { return numbers.reduce((acc, elem, i, arr) => { if ( ...

The new experimental appDir feature in Next.js 13 is failing to display <meta> or <title> tags in the <head> section when rendering on the server

I'm currently experimenting with the new experimental appDir feature in Next.js 13, and I've encountered a small issue. This project is utilizing: Next.js 13 React 18 MUI 5 (styled components using @mui/system @emotion/react @emotion/styled) T ...

Permuting sentences to create intricate anagrams

I am faced with a task of creating the correct phrase for a sentence anagram using an array of nearly 2700 strings. The list consists of almost 100k words that could potentially fit. My goal is to combine these words in groups of 1, 2, and 3 words togethe ...

Executing multiple calls with Angular's $http service and then resolving them within a loop using underscore

I am facing an issue while trying to fetch multiple data from $http inside _.each function and display the combined data in $scope.tasksData. The problem I encountered is that _.each is being executed later, causing it to return null first. Can someone pl ...

The functionality of using an Ajax call to invoke a php function on the same page is not functioning correctly

I am facing an issue where Ajax is not working in the same PHP file as the PHP function I want to call. My goal is to have a button that, when pressed, will trigger the function without reloading the page. I have placed my Ajax script at the bottom and the ...

The dynamic form functionality is experiencing issues when incorporating ng-container and ng-template

I'm currently working on a dynamic form that fetches form fields from an API. I've attempted to use ng-container & ng-template to reuse the formgroup multiple times, but it's not functioning as anticipated. Interestingly, when I revert b ...

Modifying properties through JavaScript is not possible

I created an HTML form and I'm trying to change the attributes of a div and a button but for some reason, it's not working <form> <button type='button' id='other'>Sub</button> <select id="prop"> &l ...

Setting a default value in react-select

Recently, I developed a react-select component that is compatible with redux-form. The SelectInput component looks like this: const MySelect = props => ( <Select {...props} value={props.input.value} onChange={value => props.input.on ...

Trouble with image display in a next.js project hosted on Firebase

Exploring Next.js for the first time, I recently created a website and attempted to host it on Firebase hosting. Everything seems to be working well except for one issue - the images are not rendering on the hosted site. In my project structure, there are ...

Ways to enable Urql (typescript) to accept Vue reactive variables for queries generated using graphql-codegen

I'm currently developing a Vue project that involves using urql and graphql-codegen. When utilizing useQuery() in urql, it allows for the use of Vue reactive variables to make the query reactive and update accordingly when the variables change. The ...

Utilize Bootstrap modal to input information into the DataTables library

I am trying to use a bootstrap modal to insert data, but I am encountering an error on the action index. As a result, the button that I added is not functioning correctly. Can someone please review my code to see if there are any mistakes? User Action Con ...

Making a synchronous call to a web API using JQuery

Understanding JQuery promises and deferred objects has been a bit of a challenge for me, so please bear with me. I should also mention that my application is built using React, Typescript, and ES6. Let's imagine we have an array of objects: [{ Objec ...

toggle classes using jQuery when a link is clicked

I'm currently working on a jQuery function that will apply a class to a selected link (which opens a page in an iframe) and then remove that class when another link is chosen. Previously, I received assistance from another member for a similar task in ...

initiating AngularJS ng-model pipeline on blur event

My $parser function restricts the number of characters a user can enter: var maxLength = attrs['limit'] ? parseInt(attrs['limit']) : 11; function fromUser(inputText) { if (inputText) { if (inputText.length > max ...

Ensuring that the DOM is updated exclusively following the submission of a form in

I am working on a form that contains two checkboxes. Each checkbox corresponds to an object that can toggle its 'is_active' property between true and false. When a checkbox is clicked, the DOM immediately updates: if it is checked, the object app ...

Can the warning about a missing dependency in useEffect be incorrect at times?

After using hooks for some time, I still don't quite grasp why React insists on including certain dependencies in my useEffect that I don't want. My understanding of the 'dependencies' in a useEffect hook is as follows: You should add ...

Tips for resolving an issue with mongoose Model.create becoming unresponsive indefinitely

I'm having trouble understanding why my mongoose Model.create operation isn't completing successfully. The same connection is working well with other controller functions. vscode postman I am attempting to create a new document, but my code s ...

"Error encountered when attempting to read a file from a dialog box using Electron due to

I am currently working on an electron program that requires reading a file in order to apply another program onto it. At this stage, my main goal is to successfully read and log the content of the file. Below is the code snippet I have implemented in a sc ...

The combination of Node.js, Monk, PapaParse, Bluebird, and MongoDB seems to be causing issues with updating the database

I'm currently working on a script to extract data from a CSV file and store it in my database. Everything seems to be functioning properly, except for one issue - I can't seem to get the process to end without either erasing data from the databas ...