Chron's avatar
Level 7

Do something right after a successful log in

I'm also using Laravel and Vue.

I know there's an onSuccess but it does not run until the page has finished loading.

I have a login page that redirects to intended url.

LoginPage.vue

form.submit({
	onSuccess: () => {
		console.log('1')
	}
});

HomePage.vue

<script>
console.log('2')
</script>
<template>
	Home
</template>

After a successful login, it outputs

2
1 <- i want this to be executed first

Is there a way to do this? I could use a watcher in my layout file that checks if the user is logged in, this should enforce the condition since the layout file is higher in the file hierarchy, but I want to know if there's other way to do it

1 like
3 replies
vincent15000's avatar

It depends on how you manage the redirection after a successful login.

InertiaJS can handle the redirection.

import { router } from '@inertiajs/vue3'

router.post(url, {
    onSuccess: () => {
        return Promise.all([
            this.firstTask(),
            this.secondTask()
        ])
    },
    onFinish: visit => {
        // Not called until firstTask() and secondTask() have finished
    },
})

And Laravel can handle the redirection from the backend.

1 like
martinbean's avatar

@chron What is it you actually want to do after log in, and why is the order so important?

The problem you’re having is, you’re trying to show-horn a synchronous operation in an asynchronous one (an AJAX request).

If you can tell us what is you’re trying to do, then we may be able to suggest a viable solution.

1 like
Chron's avatar
Level 7

I want to have indexedDB added on a successful login. One of the components are using it and it's giving me an error because that component gets loaded first before the onSuccess is executed. I could add it in the component that uses it, instead, but it would only execute if I visited the page that uses that component. I want to add it, right away.

I think adding a watcher on the main layout instead would do it. But I feel like it is expensive

//Layout.vue

  watch(() => page.props.auth.type, (newType, oldType) => {
    if(typeof newType === 'string') {
      const { createSchema } = idbSchema(newType);
      createSchema();
    } else {
      const { deleteSchema } = idbSchema(oldType);
      deleteSchema();
    }
  })

// etc
// idbSchema.js

export default function idbSchema(userType) {
    const schema = {
        // contains stores that `createSchema` adds
    };

    const deleteSchema = () => {
        // ...
    }

    const createSchema = () => {
        // ...
    }
    return { createSchema, deleteSchema }
}

Please or to participate in this conversation.