vuejs problem change route get userChoice in localstorage but push on the profile route before getting new userChoice? - vue.js

the problem is that on click I increments the new userChoice according to the user chosen but it pushes on the profile route before retrieving the new userChoice click.
what to do here is my template I will put everything in the same function change use the push at the end but it does not work either then I do 2 functions but it does not work either what is the solution ??
<template>
<section
class="stopPadMarg container-fluid d-md-flex justify-content-between"
>
<div class="py-5 stopPadMarg bg-primary col-md-1">
<img
src="../assets/image/icon.png"
width="60px"
class="rounded-circle"
alt="logo"
/>
</div>
<div class="largeur80">
<form class="justify-content-center form-inline py-3 my-2 my-lg-0">
<input
v-model="searchKey"
id="search"
class="form-control mr-sm-2"
type="search"
placeholder="Search"
aria-label="Search"
/>
</form>
<div>
<h3
class="backPrimaire opacity mx-1 text-primary bordurePost bordureRond"
>
<b-icon-chevron-double-down
class="mr-5 my-1 pt-1 text-secondary"
animation="cylon-vertical"
font-scale="1"
></b-icon-chevron-double-down>
Vos collegues
<b-icon-chevron-double-down
class="ml-5 my-1 pt-1 text-secondary"
animation="cylon-vertical"
font-scale="1"
></b-icon-chevron-double-down>
</h3>
</div>
<div class="hauteur">
<div class="mt-5 d-flex flex-wrap">
<div
v-for="(user, id) in filteredList"
v-bind:key="id"
class="col-md-3 d-flex flex-column align-items-center align-content-center"
>
<div #click="changeUser(user)" class="cursor">
<img
#click="changeRoute"
v-if="user.image_url !== null || ''"
:src="user.image_url"
width="100px"
height="100px"
class=" justify-content-left bordureProfil
rounded-circle"
/>
<img
v-else
src="../assets/image/icon.png"
width="100px"
class=" justify-content-left bordureProfil rounded-circle"
/>
</div>
<div>
<h5 class="mt-2">
{{ user.nom.toUpperCase() }}
</h5>
<h6 class="mb-3">{{ user.prenom.toLowerCase() }}</h6>
</div>
</div>
</div>
</div>
</div>
<div class="py-5 stopPadMarg bg-primary col-md-1">
<img
src="../assets/image/icon.png"
width="60px"
class="rounded-circle"
alt="logo"
/>
</div>
</section>
</template>
<script>
import axios from "axios";
export default {
components: {},
data() {
return {
searchKey: "",
postes: [],
users: [],
user_id: localStorage.getItem("userId"),
userChoice: localStorage.getItem("userChoice"),
};
},
async created() {
this.postes = [];
this.users = [];
await axios
.get("http://localhost:3000/postes")
.then(
(response) => ((this.postes = response.data), console.log(response))
)
.catch((error) => console.log(error));
await axios
.get("http://localhost:3000/users")
.then(
(response) => ((this.users = response.data), console.log(this.users))
)
.catch((error) => console.log(error));
await axios
.get("http://localhost:3000/users")
.then(
(response) => (
(this.userDef = response.data.find((user) => {
return user.id;
})),
console.log(this.userDef)
)
)
.catch((error) => console.log(error));
await axios
.get(`http://localhost:3000/user/${this.user_id}`)
.then(
(response) => (
(this.userConnect = response.data), console.log(this.userConnect.id)
)
)
.catch((error) => console.log(error));
await axios
.get("http://localhost:3000/commentaires")
.then(
(response) => (
(this.comments = response.data), console.log(this.comments)
)
)
.catch((error) => console.log(error));
},
computed: {
filteredList() {
return this.users.filter((user) => {
return user.nom.toLowerCase().includes(this.searchKey.toLowerCase());
});
},
},
methods: {
async changeUser(user) {
await localStorage.removeItem("userChoice");
await localStorage.setItem("userChoice", user.id);
this.$router.push(`/profil/${this.userChoice}`);
},
async changeRoute() {
await this.$router.push(`/profil/${this.userChoice}`);
},
},
};
</script>
<style></style>
and the picture here
if I press a second time on the same profile it gives it to me if I return to the colleagues page but not if I change profile there is an empty page
here picture of the routes path
in fact the route does not change profile and remains on 58 here c the profile of that which is connected and if we change number on the route it launches a page page so this is the problem with the path of the route that the we see in the browser cache

Having looked at your code it's obvious why you'd get an empty page when changing routes. Let me explain:
Your routes say this:
Register a route /profil/${userChoice} (which is a value read from localStorage).
This route definition is only read once, at page intialisation. So, when your page loads only /profil/58 will be defined, /profil/59 wont.
What you are probably looking for is route parameters:
https://router.vuejs.org/guide/essentials/dynamic-matching.html
You'd want the number part of this url to be dynamic and respond to changes.
So, instead of reading the value from localStorage, you would write:
{
path: '/profil/:user_id',
name: 'ProfilUser',
...
}
Now when your Profil components is initialized instead of accessing localStorage you read the provided value as follows:
created() {
var userChoice = this.$route.params.user_id;
}
(note it is also possible to get this param as a prop, consult the vue-router docs on how to do this)
Another thing you need to keep in mind is that you need to respond when this parameter changes. Your component will not be refreshed/remounted.
To respond to parameter changes you can do the following:
watch: {
'$route.params.user_id'() {
this.reloadAllStuff();
}
}
I would recommend to not use localStorage for this use case, let the URL parameter be the main source of truth.
Further reading:
https://qvault.io/2020/07/07/how-to-rerender-a-vue-route-when-path-parameters-change/

Related

Show login user in vue header

Show login user in vue header
I'm not using pinia, vuex, etc. When I try to log in, I saved the loginId in localstorage, but I want to retrieve it from header.vue and display the logged in user. Is there any way?
The code is lacking, but please help
If you can't give me the code on how to display the user, I'd appreciate it if you could provide a reference.
I prefer the syntax of vue3
login.vue
<template class="login">
<div class="login_box">
<h3>welcome!</h3>
<div class="login_form">
<form #submit.prevent="submit()">
<div class="login_id">
<input
v-model="state.login.loginId"
type="email"
placeholder="E-mail" />
<span class="login_icon">
<img src="../../public/images/people_icon.svg" />
</span>
</div>
<div class="login_pass">
<input
v-model="state.login.loginPw"
type="password"
placeholder="password" />
<span class="login_icon">
<img src="../../public/images/lock.svg" />
</span>
</div>
<p class="login_go">
Not id.
<router-link to="/signup">
<span>signup</span>
</router-link>
</p>
<button
class="login_btn">
Login
</button>
</form>
</div>
</div>
</template>
<script>
import axios from 'axios'
import { useRouter } from 'vue-router'
import { reactive } from 'vue'
export default {
setup() {
const router = useRouter()
const state = reactive({
login: {
loginId: '',
loginPw: '',
},
})
const submit = async () => {
const args = new FormData()
args.append('username', state.login.loginId)
args.append('password', state.login.loginPw)
console.log(state.login)
try {
await axios.post('http://127.0.0.1:8000/login/token', args, {
header: { 'Content-Type': 'application/json'}, withCredentials:true
})
.then((res) => {
console.log(res.data)
localStorage.setItem('loginId', state.login.loginId)
localStorage.setItem('access_token', `Bearer ${res.data.access_token}`)
document.cookie = `access_token=Bearer ${res.data.access_token}`
})
alert('welcome')
router.push({
name: 'home',
params: {
args
}
})
} catch (error){
alert('Login Faild')
console.error(error)
}
}
return { state, submit }
},
}
</script>
header.vue
<template>
<div class="header">
<div class="header_wrap">
<img
class="logo"
style="cursor:pointer"
#click="dashboard()" />
<ul class="gnb">
<li>
<router-link to="/service_center/notice">
Service center
</router-link>
</li>
</ul>
<ul class="tnb" v-if=loggin>
<li>
{{ $route.params.loginId}}
</li>
<li>
logout
</li>
</ul>
<ul class="tnb" v-else>
<li>
<router-link to="/login">
login
</router-link>
</li>
<li>
<router-link to="/signup">
signup
</router-link>
</li>
</ul>
</div>
</div>
</template>
<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
const dashboard = () => {
router.push({
path:'/home',
})
}
</script>
Some things that may help...
Decouple the authentication.
moving the authentication in a separate file will make it more accessible between multiple components. This can act as your dedicated non-pina, not-vuex state.
Track state as reactive and make localStorage secondary
export const loginState = reactive({
loginId: "eve.holt#reqres.in",
loginPw: "",
token: localStorage.getItem('my-token') || null,
apiState: STATES.INIT,
error: null,
});
This example will set the value from local storage if available. the rest of the application can use that value to determine the value.
then update the localStorage only within this file.
export const login = () => {
loginState.apiState = STATES.PROCESSING;
loginState.error = null;
fetch(
"https://reqres.in/api/login", {
method:"POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: loginState.loginId,
password: loginState.loginPw
})
})
.then(res => res.json())
.then(({token, error}) => {
if(error) throw new Error(error)
loginState.token = token;
localStorage.setItem('my-token', token)
loginState.apiState = STATES.SUCCESS;
})
.catch(error => {
console.error(error);
loginState.error = error.message;
loginState.apiState = STATES.ERROR;
})
}
export const logout = () => {
loginState.token = null;
login.apiState = STATES.INIT;
localStorage.removeItem('my-token')
}
here only login and logout update the state, the rest of the app can use other functions.
make helpers available
export const isLoggedIn = computed(() => loginState.token !== null);
export const hasError = computed(() => loginState.error !== null);
export const isProcessing = computed(() => loginState.apiState === STATES.PROCESSING);
instead of checking the state directly, you can rely on derived state using computed.
in fact, I would not store username and password in a state, but have them passed in in the login function and the state can then be internal
here is an example
note that the example uses fetch instead of and an available api from https://reqres.in/ to make it work with fewer dependencies

Nuxt-content not working with asyncData in a component

I'm trying to fetch content from my content/blog folder but I can't make it work in the components/menu.vue page since it's a component ?
This is working in the page/index.vue but not in components/menu.vue. Why?
I'm new to all this and maybe I'm doing something wrong here, maybe I'm not able to fetch content from a component... I don't know.
<template>
<div class="container">
<div class="articles">
<div class="article" v-for="article of articles" :key="article">
<nuxt-link :to="{ name: 'slug', params: { slug: article.slug } }">
<div class="article-inner">
<img :src="require(`~/assets/${article.img}`)" alt="" />
<div class="detail">
<h3>{{ article.title }}</h3>
<p>{{ article.description }}</p>
</div>
</div>
</nuxt-link>
</div>
</div>
</div>
</template>
<script>
export default {
async asyncData ({ $content, params }) {
const articles = await $content('blog', params.slug)
.only(['title', 'description', 'img', 'slug'])
.sortBy('createdAt', 'asc')
.fetch()
console.log('bongo')
return {
articles
}
},
data () {
return {
num: this.$route.name
}
},
computed: {
currentRouteName () {
return this.$route.name
}
}
}
</script>
As written here: https://nuxtjs.org/docs/features/data-fetching#async-data
asyncData is only available for pages and you don't have access to this inside the hook.
So yes you can use asyncData only in a page.
An alternative would be to use a non-blocking fetch() hook as shown here: https://nuxtjs.org/docs/features/data-fetching#accessing-the-fetch-state

How to use Axios with Vue 3 Composition API

I am attempting to build a Pokemon filtered search app with Vue 3 and Composition API based on the following tutorial: https://www.youtube.com/watch?v=QJhqr7jqxVo. (GitHub: https://github.com/ErikCH/PokemonVue)
The fetch method used in the search component includes a reduce() function to handle urlIdLookup based on a specific id assigned to each Pokemon in the API response:
const state = reactive({
pokemons: [],
filteredPokemon: computed(()=> updatePokemon()),
text: "",
urlIdLookup: {}
});
fetch("https://pokeapi.co/api/v2/pokemon?offset=0")
.then((res) => res.json())
.then((data) => {
console.log(data);
state.pokemons = data.results;
state.urlIdLookup = data.results.reduce((acc, cur, idx)=>
acc = {...acc, [cur.name]:idx+1 }
,{})
console.log('url',state.urlIdLookup+1)
});
urlIdLookup is then passed into the route used to display selected Pokemon info:
<div
class="ml-4 text-2xl text-blue-400"
v-for="(pokemon, idx) in filteredPokemon"
:key="idx"
>
<router-link :to="`/about/${urlIdLookup[pokemon.name]}`">
{{ pokemon.name }}
</router-link>
</div>
Instead of using the above fetch setup, I wish to use Axios to handle the request and response from the Pokemon API. After installing Axios in the project and importing it into the component, I added a new fetchPokemon method:
const fetchPokemon = () => {
axios.get('https://pokeapi.co/api/v2/pokemon?offset=0')
.then(response => {
state.pokemons = response.data
})
}
onMounted(() => {
fetchPokemon()
})
While using Axios in this new fetch method, I want to handle urlIdLookup similar to the previous fetch setup, but without using the reduce() method and de-structured accumulator, if possible. How can I go about using Axios to retrieve the urlId of each Pokemon, then pass that urlId into the "about" route in the template?
Here is the full component:
<template>
<div class="w-full flex justify-center">
<input placeholder="Enter Pokemon here" type="text"
class="mt-10 p-2 border-blue-500 border-2" v-model="text" />
</div>
<div class="mt-10 p-4 flex flex-wrap justify-center">
<div
class="ml-4 text-2xl text-blue-400"
v-for="(pokemon, idx) in filteredPokemon"
:key="idx"
>
<router-link :to="`/about/${urlIdLookup[pokemon.name]}`">
{{ pokemon.name }}
</router-link>
</div>
</div>
</template>
<script>
import axios from 'axios';
import { reactive, toRefs, computed, onMounted } from "vue";
export default {
setup() {
const state = reactive({
pokemons: [],
filteredPokemon: computed(()=> updatePokemon()),
text: "",
urlIdLookup: {}
});
const fetchPokemon = () => {
axios.get('https://pokeapi.co/api/v2/pokemon?offset=0')
.then(response => {
state.pokemons = response.data
})
}
onMounted(() => {
fetchPokemon()
})
// fetch("https://pokeapi.co/api/v2/pokemon?offset=0")
// .then((res) => res.json())
// .then((data) => {
// console.log(data);
// state.pokemons = data.results;
// state.urlIdLookup = data.results.reduce((acc, cur, idx)=>
// acc = {...acc, [cur.name]:idx+1 }
// ,{})
// console.log('url',state.urlIdLookup+1)
// });
function updatePokemon(){
if(!state.text){
return []
}
return state.pokemons.filter((pokemon)=>
pokemon.name.includes(state.text)
)
}
return { ...toRefs(state), fetchPokemon, updatePokemon };
}
};
</script>
If I understood you correctly take a look at following snippet:
const { reactive, toRefs, computed, onMounted } = Vue
const { axioss } = axios
const app = Vue.createApp({
setup() {
const state = reactive({
pokemons: [],
filteredPokemon: computed(() => updatePokemon()),
text: "",
urlIdLookup: {},
});
const fetchPokemon = () => {
axios
.get("https://pokeapi.co/api/v2/pokemon?offset=0")
.then((response) => {
state.pokemons = response.data.results; // 👈 get just results
});
};
fetchPokemon();
// 👇 function to get index
const getPokemonId = (item) => {
return state.pokemons.findIndex((p) => p.name === item);
};
function updatePokemon() {
if (!state.text) {
return [];
}
return state.pokemons.filter((pokemon) =>
pokemon.name.includes(state.text)
);
}
// 👇 return new function
return { ...toRefs(state), fetchPokemon, updatePokemon, getPokemonId };
},
})
app.mount('#demo')
<script src="https://unpkg.com/vue#3.2.29/dist/vue.global.prod.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.26.1/axios.min.js" integrity="sha512-bPh3uwgU5qEMipS/VOmRqynnMXGGSRv+72H/N260MQeXZIK4PG48401Bsby9Nq5P5fz7hy5UGNmC/W1Z51h2GQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div id="demo">
<div class="w-full flex justify-center">
<input
placeholder="Enter Pokemon here"
type="text"
class="mt-10 p-2 border-blue-500 border-2"
v-model="text"
/>
</div>
<div class="mt-10 p-4 flex flex-wrap justify-center">
<div
class="ml-4 text-2xl text-blue-400"
v-for="(pokemon, i) in filteredPokemon"
:key="i"
>
<!-- // 👇 call function to get index -->
<router-link :to="`/about/${getPokemonId(pokemon.name)}`">
{{ pokemon.name }} - id {{ getPokemonId(pokemon.name) }}
</router-link>
</div>
</div>
</div>
it seem id is not necessary, why not use name be id. if you want use interger
be must, you can foreach results set index be id to each item, then
<router-link :to="`/about/${pokemon.id}`">
{{ pokemon.name }}
</router-link>

Display an random Object from API Vue.js

I need to display a random object from an array. The array comes from the API.
<template>
<div class="container">
<div class="box">
<p class="name"> {{chosenName.title}} </p>
<p class="description"> {{chosenName.description}} </p>
<hr>
<img v-bind:src="chosenName.urlToImage" alt="">
<p class="author"> {{chosenName.author}} </p>
</div>
<div class="box">
<p class="name"> {{chosenName.title}} </p>
<p class="description"> {{chosenName.description}} </p>
<hr>
<img v-bind:src="chosenName.urlToImage" alt="">
<p class="author"> {{chosenName.author}} </p>
</div>
<button v-on:click="choose" id="choose-button">One more time</button>
</div>
</template>
#Options({
props: {
msg: String
},
data() {
return {
artworks: [],
errors: [],
chosenName: '',
}
},
created() {
axios.get(url)
.then(response => {
this.artworks = response.data.names;
})
.catch(e => {
this.errors.push(e)
})
},
methods: {
choose() {
const chosenNumber = Math.floor(Math.random() * this.artworks.length);
this.chosenName = this.artworks[chosenNumber];
console.log(chosenNumber)
}
}
})
I managed to display the random object on click. What I would like to have is the object appearing at page load. I tried to put the function in the mounted cycle but with no good result like this ---> this.choose();
you need to call this.choose() in your mounted/created hook after the promise is fulfilled if you want to make it appear on the page load as well. e.g:
mounted () {
axios.get(url)
.then(response => {
this.artworks = response.data.names;
this.choose()
})
.catch(e => {
this.errors.push(e)
})
}

how to create autocomplete component in vue js?

I am facing an issue with my autocomplete component. whenever i type anything into the input field the input is reset.I mean it does not let me type anything.It just keeps getting reset before i could fully type anything.
main.js
Vue.component('g-autocomplete', {
props: ['list','value','title'],
data() {
return {
input: '',
}
},
template: `<template>
<div class="autocomplete">
<input style="font-size: 12pt; height: 36px; width:1800px; " type="text" v-model="input" #input="handleInput"/>
<ul v-if="input" >
<li v-for="(item, i) in list" :key="i" #click="setInput(item)" >
<!-- {{ autocompleteData }} -->
<template v-if="title!='manager'">
<div class="container">
<p>
<b>ID:</b>
{{item.id}}
</p>
<p>
<b>Description:</b>
{{item.description}}
</p>
</div>
</template>
<template v-else>
<div class="container">
<p>
<b>ID:</b>
{{item.id}}
</p>
<p>
<b>First Name:</b>
{{item.firstName}}
</p>
<p>
<b>Last Name:</b>
{{item.lastName}}
</p>
</div>
</template>
</li>
</ul>
</div>
</template>`,
methods: {
handleInput(e) {
console.log('inside handleInput')
this.$emit('input', e.target.value)
},
setInput(value) {
console.log('inside setInput')
this.input = value
this.$emit('click', value)
},
},
watch: {
$props: {
immediate: true,
deep: true,
handler(newValue, oldValue) {
console.log('new value is'+newValue)
console.log('old value is'+oldValue)
console.log('value inside handler'+this.value)
console.log('list inside handler'+this.list)
console.log('title inside handler'+this.title)
this.input=this.value
}
}
// msg(newVal) {
// this.msgCopy = newVal;
// }
}
})
i reuse the above component from diffrent vue pages's like this-
<b-field label="Custom Business Unit">
<g-autocomplete v-on:input="getAsyncDataBusinessUnit" v-on:click="(option) => {updateValue(option.id,'businessUnit')}" :value="this.objectData.businessUnit" :list="dataBusinessUnit" title='businessUnit' >
</g-autocomplete>
</b-field>
my debounce function that is called when something is typed into the input field.
getAsyncDataBusinessUnit: debounce(function(name) {
if (!name.length) {
this.dataBusinessUnit = [];
return;
}
this.isFetching = true;
api
.getSearchData(this.sessionData.key,`/businessunit/?filter={id} LIKE '%25${name}%25' OR {description} LIKE '%25${name}%25'`)
.then(response => {
this.dataBusinessUnit = [];
response.forEach(item => {
this.dataBusinessUnit.push(item);
});
})
.catch(error => {
this.dataBusinessUnit = [];
throw error;
})
.finally(() => {
this.isFetching = false;
});
}, 500),
what could be the issue here ? Also i noticed that the issue doesn't happen if i comment out the body of the debounce function.So therefore i feel there is something in the debounce function that is causing this.I will try to isolate the problem but i want to understand what exactly is causing this issue. Plz help?