Try to update sessions value using forEach loop - vue.js

In an admin profile, I have a list where I display the session history. I created a button to delete all sessions where isActive = false. To see the result I have to refresh my page. I want the data updated dynamically.
I'm trying to use a forEach loop to check if session isActive = false, delete the session and update sessions.
Here it's what I have done but it only removes 2-3 raw of sessions. It should remove ALL inactive sessions.
import { defineStore } from "pinia";
import axios from "axios";
export const useAuthenticationStore = defineStore({
id: "authenticationStore",
state: () => ({
session: null,
sessions: [],
loaders: {
login: false,
logout: false,
retrieveSession: false,
retrieveSessions: false,
deleteInactiveSessions: false,
},
}),
getters: {
admin: (state) => state.session?.admin,
},
actions: {
async deleteInactiveSessions(id) {
const apiRoute = `/api/inactive-sessions`;
try {
this.loaders["deleteInactiveSessions"] = true;
const deletedInactiveSessions = await axios.delete(apiRoute);
console.log(deletedInactiveSessions);
this.sessions.forEach(() => {
const deletedInactiveSessionsIndex = this.sessions.findIndex(
(session) => session.id === deletedInactiveSessions.id
);
return this.sessions.splice(deletedInactiveSessionsIndex);
});
} finally {
this.loaders["deleteInactiveSessions"] = false;
}
},
This is what deletedInactiveSessions returns me:
{data: {…}, status: 200, statusText: 'OK', headers: AxiosHeaders, config: {…}, …}
config
:
{transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …}
data
:
{count: 3}
headers
:
AxiosHeaders {access-control-allow-credentials: 'true', access-control-allow-origin: '*', connection: 'close', content-length: '11', content-security-policy: "default-src 'self';base-uri 'self';block-all-mixed… https: 'unsafe-inline';upgrade-insecure-requests", …}
request
:
XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status
:
200
statusText
:
"OK"
[[Prototype]]
:
Object

Related

How can I log in as a user with nuxt.auth?

I currently have the following nuxt.auth configuration.
auth: {
strategies: {
cookie: {
endpoints: {
login: { url: '/api/login', method: 'post' },
},
},
},
},
When login is ok, the response is in json format with the following data
{'user': 'Tlaloc-Es'}
On the login page I have the following code:
this.$auth
.loginWith('cookie', {
data: {
email: this.user_email,
password: this.user_password,
remember: this.remember,
},
})
.then((data) => {
const response = data.data.data;
this.$auth.setUser(response.user);
console.log(response.user);
console.log(this.$auth.loggedIn);
});
The problem is this.$auth.loggedIn always returns false.
I guess that auth doesn't set the user as logged, but I don't know any other steps I need part of:
this.$auth.setUser(response.user);
After a call, logging in browser stores the following cookies:
auth._token.cookie -> true
session -> session token
auth.strategy -> 'cookie'
auth._token_expiration.cookie -> false
How can I set the user as logged?
EDIT
If I execute the logout this value
auth._token.cookie
turn to false, but the session still is stored and anyway
this.$auth.loggedIn
return false.
EDIT
Another try:
auth: {
redirect: {
login: '/login',
logout: '/login',
home: '/',
},
strategies: {
cookie: {
cookie: {
name: 'session',
},
user: {
property: false,
autoFetch: false,
},
endpoints: {
login: { url: '/api/login', method: 'post' },
logout: { url: '/api/logout', method: 'post' },
},
},
},
},
async signIn() {
const succesfulLogin = await this.$auth.loginWith('cookie', {
data: {
email: this.user_email,
password: this.user_password,
remember: this.remember,
},
});
if (succesfulLogin) {
const response = succesfulLogin.data.data;
await this.$auth.setUser({ user: response.user });
console.log(this.$auth.loggedIn);
//await this.$auth.logout();
}
},
This is after login:
reponse cookie
Thanks.
you should try setting set this.$auth.loggedIn = true to true after receiving the data
this.$auth
.loginWith('cookie', {
data: {
email: this.user_email,
password: this.user_password,
remember: this.remember,
},
})
.then((data) => {
const response = data.data.data;
this.$auth.setUser(response.user);
this.$auth.loggedIn = true
console.log(response.user);
console.log(this.$auth.loggedIn);
});
Finally works with the following configuration:
auth: {
redirect: {
login: '/login',
logout: '/login',
home: '/',
},
strategies: {
cookie: {
options: {
httpOnly: true,
path: '/',
},
user: {
property: false,
autoFetch: false,
},
endpoints: {
login: { url: '/api/login', method: 'post' },
logout: { url: '/api/logout', method: 'post' },
},
},
},
},

nuxt Vue Components, computed value is "undefined"

I am trying to get data through NUXT Api.
also want to return it to the computed property.
I'm sure I missed some stupid mistake or something simple.
I appreciate help.
async asyncData ({ app, params }) {
let listdata = []
try {
const Id = params.someid
const { data } = await app.$axios.get(`/api/some/path/me/${Id}`)
listdata = data
return {
listdata
}
} catch (e) {
return (e)
}
},
data () {
return {
}
}
computed here.
computed: {
returnlist () {
const list = this.listdata
return list
}
},
and result undefined
listdata console.log here
{data: Array(4), status: 200, statusText: 'OK', headers: {…}, config: {…}, …}
config: {url: '/api/some/path/me/Obj_id', method: 'get', headers: {…}, baseURL: '/', transformRequest: Array(1), …}
data: Array(4)
0: {partiant: Array(2), _id: 'Obj_id', sender: 'Obj_id', …}
1: {partiant: Array(2), _id: 'Obj_id', sender: 'Obj_id', …}
2: {partiant: Array(2), _id: 'Obj_id', sender: 'Obj_id', …}
3: {partiant: Array(2), _id: 'Obj_id', sender: 'Obj_id', …}
length: 4
...
status: 200
statusText: "OK"
[[Prototype]]: Object

loss of an object as reactive method

I am creating an application in which a user can create how to update a project, the application is being done with Vue 3 and Go, but I find a problem and that is that when I want to obtain the project data and then update the information it is generated An error, and it is that when obtaining the data from the api it does well because it shows me the information I want, the problem is when I refresh the page because the data is lost immediately.
this is an example of what the api returns me:
{
"id_project": 3,
"name": "gbhnju",
"description": "derftgyh",
"start_date": "2021-08-06T00:00:00Z",
"end_date": "2021-08-17T00:00:00Z",
"created_at": "2021-08-06T15:57:19.27Z",
"updated_at": "0001-01-01T00:00:00Z"
}
These values are returned, but when I update the page they are lost.
This is the component that makes the request to obtain the project data:
export default {
components: { EditProject },
setup() {
const route = useRoute();
const project = reactive({});
onMounted(() => {
fetch(`http://localhost:8000/api/v1/projects/${route.params.id}`)
.then((res) => res.json())
.catch((error) => console.error(error))
.then((data) => {
Object.assign(project, data);
});
});
return {
project,
};
},
};
</script>
And this is the component which receives the information to be able to update the data:
<script>
import { ref, toRef, toRefs } from '#vue/reactivity';
import { useRoute, useRouter } from 'vue-router';
export default {
props: {
project: {
type: Object,
required: true,
},
},
setup(props) {
const project = toRefs(props.project);
console.log(project);
const content = toRef(props, 'project');
const name = toRef(content.value, 'name');
const description = toRef(content.value, 'description');
const endProject = toRef(content.value, 'endProject');
const user = toRef(content.value, 'user');
const users = ref();
const route = useRoute();
const router = useRouter();
fetch(`http://localhost:8000/api/v1/users/selected_user`)
.then((data) => data.json())
.catch((error) => console.error(error))
.then((response) => {
users.value = response;
});
const editProject = () => {
if (
name.value === '' ||
description.value === '' ||
endProject.value === '' ||
user.value === ''
) {
console.log('error');
return;
}
fetch(`http://localhost:8000/api/v1/projects/${route.params.id}`, {
method: 'PUT',
body: JSON.stringify({
name: name.value,
description: description.value,
end_date: new Date(endProject.value.replace('-', '/')),
user: {
id_user: user.value,
},
}),
headers: {
'Content-Type': 'application/json',
},
});
router.push({
name: 'Project',
});
};
return {
name,
description,
endProject,
user,
users,
editProject,
};
},
};
</script>
This is the sample code to display the data by console:
const end_date = toRefs(props.project, 'end_date');
console.log(end_date);
What it shows me by console is the following:
created_at: ObjectRefImpl {_object: Proxy, _key: "created_at", __v_isRef: true}
description: ObjectRefImpl {_object: Proxy, _key: "description", __v_isRef: true}
end_date: ObjectRefImpl
__v_isRef: true
_key: "end_date"
_object: Proxy {id_project: 3, name: "gbhnju", description: "derftgyh", start_date: "2021-08-06T00:00:00Z", end_date: "2021-08-17T00:00:00Z", …}
value: "2021-08-17T00:00:00Z"
[[Prototype]]: Object
id_project: ObjectRefImpl {_object: Proxy, _key: "id_project", __v_isRef: true}
name: ObjectRefImpl {_object: Proxy, _key: "name", __v_isRef: true}
progress: ObjectRefImpl {_object: Proxy, _key: "progress", __v_isRef: true}
project_state: ObjectRefImpl {_object: Proxy, _key: "project_state", __v_isRef: true}
start_date: ObjectRefImpl {_object: Proxy, _key: "start_date", __v_isRef: true}
updated_at: ObjectRefImpl {_object: Proxy, _key: "updated_at", __v_isRef: true}
user: ObjectRefImpl {_object: Proxy, _key: "user", __v_isRef: true}
user_creation: ObjectRefImpl {_object: Proxy, _key: "user_creation", __v_isRef: true}
But when I want to show the value of the toRef by console it generates an undefined one, or if I update the page the obtejo is as if it were lost:
console.log(end_date.value);
This is what it shows me when I update the page:
[[Prototype]]: Object
constructor: ƒ Object()
hasOwnProperty: ƒ hasOwnProperty()
isPrototypeOf: ƒ isPrototypeOf()
propertyIsEnumerable: ƒ propertyIsEnumerable()
toLocaleString: ƒ toLocaleString()
toString: ƒ toString()
valueOf: ƒ valueOf()
__defineGetter__: ƒ __defineGetter__()
__defineSetter__: ƒ __defineSetter__()
__lookupGetter__: ƒ __lookupGetter__()
__lookupSetter__: ƒ __lookupSetter__()
get __proto__: ƒ __proto__()

Nuxt-auth doesn't see any cookies

Nuxt-auth doesn't see any cookies. Doesn't 'connect.sid' cookie.
nuxt.config.js auth settings:
auth: {
strategies: {
cookie: {
cookie: {
prefix: '',
name: 'test',
},
options: {
expires: new Date(new Date().getTime() + 20000000000).getTime(),
maxAge: 31622400,
},
user: {
property: 'data',
autoFetch: false,
},
endpoints: {
login: { url: '/auth/login', method: 'post', withCredentials: true },
logout: { url: '/auth/logout', method: 'delete' },
},
},
},
},
However browser has the cookies (not 'httpOnly'):
'auth._token.cookie': true
'connect.sid': '213lkj123123fsdsf'
'auth.strategy': 'cookie'
'auth._token_expiration.cookie': false
'i18n_redirected': 'en'

I can't Integrat Sweet Alert After Axios Post action vueJs

i want to integrate this toast only if axios post is executed. i placed it like that and it's shown up even if my post axios function is not working.
how can i fix that ?
My code:
methods: {
addRinvoice: function () {
const toast = swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 9000
});
axios.post('/addrinvoice', this.rinvoice)
.then(response => {
toast({
type: 'success',
title: 'Invoice added in Database'
}),
console.log(response.data);
if (response.data.etat) {
this.rinvoice = {
id: 0,
amount: response.data.etat.amount,
};}})
.catch(error => {
console.log('errors: ', error)
}) },
Just put your call invoking the toast method inside your then() method:
methods: {
addRinvoice: function () {
axios.post('/addrinvoice', this.rinvoice)
.then(response => {
const toast = swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 9000
});
toast({
type: 'success',
title: 'Invoice added in Database'
}),
console.log(response.data);
if (response.data.etat) {
this.rinvoice = {
id: 0,
amount: response.data.etat.amount,
};}})
.catch(error => {
console.log('errors: ', error)
})
},
place it inside then after getting response successfully like :
then(response=>{
...
const toast = swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 9000
});
toast({
type: 'success',
title: 'Invoice added in Database'
}
}