Laravel + Vue ssr. Prefetch data - laravel

I'm trying to make application lavevel + vue with server side render. I have found this manual and it works perfect. Bu there is a small problem. I need fetch data before page loading for SEO issues and I found official vue ssr manual for prefetch. But it does not work. I only see error in the console
entry-client.js:6952 [Vue warn]: Cannot find element: #app.
my entry-server.js
import {createApp} from './app'
export default context => {
return new Promise((resolve, reject) => {
const {app, router, store} = createApp();
router.push(context.url)
router.onReady(() => {
// This `rendered` hook is called when the app has finished rendering
context.rendered = () => {
context.state = store.state
}
resolve(app)
}, reject)
}).then(app => {
renderVueComponentToString(app, (err, res) => {
print(res);
});
})
.catch((err) => {
print(err);
})
}
Are there any idea how solve this problem?
Looks like Promise does not work
Laravel 5.7 and Vue 2.6.6

Related

Laravel Sanctum/Vuex Uncaught Error Vue Router Navigation Guard

Can anyone advise on this issue?
I've got a Laravel app with a Vue front-end, connecting to the API using Laravel Sanctum. (within the same application) I'm trying to set up the authentication guards so routes can only be accessed after authentication with the API.
I'm connecting through the state action like so:
async getAuthenticatedUser({ commit }, params) {
await axios.get('api/auth-user', { params })
.then(response => {
commit('SET_AUTHENTICATED', true)
commit('SET_AUTHENTICATED_USER', response.data)
localStorage.setItem('is-authenticated', 'true')
return Promise.resolve(response.data)
})
.catch(error => {
commit('SET_AUTHENTICATED', false)
commit('SET_AUTHENTICATED_USER', [])
localStorage.removeItem('is-authenticated')
return Promise.reject(error.response.data)
})
},
The state authenticated property is set as follows:
const state = () => ({
authenticated: localStorage.getItem('is-authenticated') || false,
authUser: [],
})
I have the following guard checking the auth. If I'm not signed in the app correctly redirects me back to the login screen when I access a route with the requiresAuth attribute.
However when I attempt to log in, I get Redirected when going from "/login" to "/dashboard" via a navigation guard.
router.beforeEach((to, from, next) => {
if (to.matched.some((record) => record.meta.requiresAuth)) {
if (store.getters["Auth/isAuthenticated"]) {
next()
return
}
next('/login')
}
if (to.matched.some((record) => record.meta.requiresVisitor)) {
if (! store.getters["Auth/isAuthenticated"]) {
next()
return
}
next('/dashboard')
}
next()
})
If it's safe to ignore, and you are using vue-router ^3.4.0, you can do:
import VueRouter from 'vue-router'
const { isNavigationFailure, NavigationFailureType } = VueRouter
...
this.$router.push(fullPath).catch(error => {
if (!isNavigationFailure(error, NavigationFailureType.redirected)) {
throw Error(error)
}
})

get user permissions with laravel vue rest api

I'm trying to get all user permissions with Laravel for backend and vuejs for frontend.
How can i get this from api to vue? what is the best choice?
I tried to get them with below code but shows me error
In the permissionMixin:
import PermissionDataService from '../../Servieces/PermissionDataService'
export default {
methods: {
checkPermission() {
let permissions;
PermissionDataService.get("user_permissions")
.then((response) => {
permissions= response.data;
})
.catch((error) => {
console.debug(error)
});
return hasAccess;
}
}
}
and that is how i used it in main.js:
import permission from "#/core/mixins/permissionMixin";
Vue.mixin(permission);
window.Laravel = this.checkPermission();
console.debug(Laravel)
Vue.directive('can', function (el, binding) {
return Laravel.permissions.indexOf(binding) !== -1;
});
but always shows me this error:
Uncaught TypeError: can't access property "defaults", a.default.axios is undefined
I am totally sure the endpoint is ok
ANY Idea?
Finally solved.
I had to put
window.Laravel = this.checkPermission();
into one of layout files

Get vuex store state after dispatching an action

I'm creating a chat application in Laravel 6 + Vue + Vuex. I want make a call to vuex store and get a state after a dispatch actions is complete and then I want to do some processing on that state in my vue component.
In ChatWindow component
mounted: function () {
this.$store.dispatch('setContacts').then(() => {
console.log('dispatch called')
// I want to call the getter here and set one of the data property
});
}
action.js
setContacts: (context) => {
axios.post('/users').then(response => {
let users = response.data;
// consoled for testing
console.log(users);
context.commit('setContacts', users);
});
}
mutators.js
setContacts: (state, users) => {
state.contacts = users;
},
Please see the screenshot below. The then method of dispatch is running before setContacts in action.js.
I need to call the getter after completing dispatch action. (which will effectively set the contacts state). Then, I want to get the contacts through getContacts getter like this.
getters.js
getContacts: (state) => {
return state.contacts;
}
I also tried calling computed property in then in mounted and it didn't work. Also, shouldn't 'dispatch called' in mounted run after console.log of setContacts in action.js as it is in then method? Thanks!
Maybe you could wrap axios call inside another promise.
return new Promise((resolve, reject) => {
axios.post('/users')
.then(response => {
let users = response.data;
// consoled for testing
console.log(users);
context.commit('setContacts', users);
resolve('Success')
})
.catch(error => {
reject(error)
})
})
And then
this.$store.dispatch('setContacts')
.then(() => {
console.log('dispatch called')
console.log('getter ', this.$store.getters.contacts)
});
Let me know what happens. It was working for a small demo that I tried.

how to use axios on nativescript-vue

hello i am trying fetch data from my backend but its look like not working also can't debug whats happening on load
i did try something like this
import axios from 'axios/dist/axios';
axios.get('http://api.chillwisper.tk/api/videos')
.then(response => {
console.log(response.data);
this.videos = response.data.data
})
nothing happen no console logs nothing
i also tried this
fetch("http://api.chillwisper.tk/api/videos")
.then((response) => {
console.log(response.data);
console.log('this is test shit')
this.videos = response.data.data
})
.catch((e) => {
console.log(e.response)
});
still not work how can do this i am new in nativescript but i know vue

302 Found on Laravel in GET request made by cross-fetch on react

I have a component with a table, when this component mounts I would like to make a request to get data that fills the table.
In my table component:
componentDidMount() {
const { fetchTransactions } = this.props;
fetchTransactions()
}
This came from (I'm using redux):
const mapDispatchToProps = dispatch => ({
fetchTransactions: value => dispatch(fetchTransactions())
})
And the action:
export function fetchTransactions() {
return function (dispatch) {
dispatch(requestTransactions())
return fetch('/getTransactions')
.then(
response => response.json(),
error => console.log('An error occurred.', error)
)
.then(json => dispatch(receiveTransactions(json)))
}
}
When the component mounts, the action is dispatched and the fetch too, but the response is a 302 found as you can see here:
Using the browser it work as I expect:
Any ideas? thank you.

Resources