stocking api response.data in localStorage on click vuejs - javascript

My goal is to store a specific data in the localStorage when I click on a link
but log i get is either undefined or absolutely nothing.
<li v-for="(categorie, index) in categories" :key="index">
<a href="./currentCategory" #click.prevent="getCategory()">
<img class="categorie-img" :src="categorie.strCategoryThumb" >
<p>{{ categorie.strCategory }}</p>
</a>
</li>
data() {
return {
categories: []
}
},
methods: {
getAllCategories() {
axios
.get('https://www.themealdb.com/api/json/v1/1/categories.php')
.then((response) => {
console.log( response.data);
this.categories = response.data.categories;
}).catch(error => {
console.log(error);
alert("api can't be reached");
})
},
getCategory() {
localStorage.setItem('currentCategory', this.categorie.strCategory );
}
},
I am using this API https://www.themealdb.com/api/json/v1/1/categories.php
I guess this.categorie.strCategory is incorrect but i really cant figure it out
I also tried this.categories.strCategory

Try to pass category
#click.prevent="getCategory(categorie)
then save it
getCategory(cat) {
localStorage.setItem('currentCategory', cat );
}

Found the answer thanks to #Nikola Pavicevic
had to pass a category to the click event
#click.prevent="getCategory(categorie.strCategory)
and pass it to the function
getCategory(cat) {
localStorage.setItem('currentCategory', cat);
}

Related

Pull refresh does not update the list

My card does not get the latest data from firestore even with pull refresh implemented in quasar
<q-pull-to-refresh #refresh="refresh">
<q-card
class="q-ma-md"
bordered
v-for="announcement in announcements"
:key="announcement.key"
>
<q-card-section>
<div class="text-h6">{{announcement.TITLE}}</div>
<div class="text-subtitle2">{{announcement.CONTENT}}</div>
</q-card-section>
</q-card>
</q-pull-to-refresh>
here is my script and methods
data() {
return {
announcements: [],
};
},
//methods
retrieveAnnouncements() {
firebase
.firestore()
.collection("announcement")
.get()
.then(snapShot => {
snapShot.forEach(element => {
const { TITLE, CONTENT, AUTHOR } = element.data();
//add retrieved data in announcement
this.announcements.push({
key: element.id,
TITLE,
CONTENT,
AUTHOR
});
});
});
},
here is my refresh method that tries to update the card of the current page
refresh(done) {
setTimeout(() => {
(this.announcements = null), done();
}, 1000);
},
created() {
this.retrieveAnnouncements();
}
Does your refresh function call retrieveAnnouncements?
It looks like it's only called on created

update follow status after axios request in Vue

i need to update the follow an unfollow button after axios request
<template>
<div v-if="isnot">
<a href="#" #click.prevent="unfellow" v-if="isfollowing" >unFellow</a>
<a href="#" #click.prevent="fellow" v-else >Fellow</a>
</div>
</template>
My Methods
fellow () {
axios.post(`/#${this.follower}/follow/`)
},
unfellow () {
axios.post(`/#${this.follower}/unfollow/`)
},
}
A basic example:
fellow () {
var self = this;
axios.post(`/#${this.follower}/follow/`)
.then(function (response) {
self.isfollowing = true;
})
.catch(function (error) {
console.log( error.response.data);
});
},
Axios has a series of methods you can execute after the response arrives. In the case of a post call your structure can be something like this
axios.post(YOUR ROUTE)
.then(function (response) {
//executes after getting a successful response
// here you can change your 'isfollowing' variable accordingly
})
.catch(function (error) {
//executes after getting an error response
});
Fast way:
<template>
<div v-if="isnot">
<a href="#" #click.prevent="fellowUnfellow" v-if="isfollowing" >{{isfollowing ? "unFellow" : "Fellow"}}</a>
</div>
</template>
fellowUnfellow () {
axios.post(`/#${this.follower}/follow/`).then(function (r) {
this.isfollowing = !this.isfollowing;
})
}

Vue JS unable to display to DOM the returned data of method

Template html
<div class="item" v-for="n, index in teamRoster">
<span> {{ getFantasyScore(n.personId) }} </span>
</div>
Method
getFantasyScore(playerId) {
if(playerId) {
axios.get(config.NBLAPI + config.API.PLAYERFANTASYSCORE + playerId)
.then( (response) => {
if( response.status == 200 ) {
console.log(response.data.total)
return response.data.total;
}
});
}
}
I'm trying to display the returned data to DOM but it doesnt display anything. But when I try to console log the data is displays. How can I be able to display it. What am I missing?
Problem is, your getFantasyScore method doesn't return anything and even then, the data is asynchronous and not reactive.
I would create a component that loads the data on creation. Something like
Vue.component('fantasy-score', {
template: '<span>{{score}}</span>',
props: ['playerId'],
data () {
return { score: null }
},
created () {
axios.get(config.NBLAPI + config.API.PLAYERFANTASYSCORE + this.playerId)
.then(response => {
this.score = response.data.total
})
}
})
and then in your template
<div class="item" v-for="n, index in teamRoster">
<fantasy-score :player-id="n.personId"></fantasy-score>
</div>
You shouldn't use methods for AJAX results because they are async. You could retrieve the full teamRoster object and then add this to your div:
<div class="item" v-for="fantasyScore in teamRoster" v-if="teamRoster">
<span> {{ fantasyScore }} </span>
</div>

Laravel + Vue.js. Load more data when i click on the button

i have problem. When I click the button, it receives an entire database, but I want laod part database. How can I do this?
For example: After every click I would like to read 10 posts.
Thx for help.
Messages.vue:
<div class="chat__messages" ref="messages">
<chat-message v-for="message in messages" :key="message.id" :message="message"></chat-message>
<button class="btn btn-primary form-control loadmorebutton" #click="handleButton">Load more</button>
</div>
export default{
data(){
return {
messages: []
}
},
methods: {
removeMessage(id){...},
handleButton: function () {
axios.get('chat/messagesmore').then((response) => {
this.messages = response.data;
});
}
},
mounted(){
axios.get('chat/messages').then((response) => {
this.messages = response.data
});
Bus.$on('messages.added', (message) => {
this.messages.unshift(message);
//more code
}).$on('messages.removed', (message) => {
this.removeMessage(message.id);
});
}
}
Controller:
public function index()
{
$messages = Message::with('user')->latest()->limit(20)->get();
return response()->json($messages, 200);
}
public function loadmore()
{
$messages = Message::with('user')->latest()->get();
// $messages = Message::with('user')->latest()->paginate(10)->getCollection();
return response()->json($messages, 200);
}
paginate(10) Loads only 10 posts
You can do it like this:
<div class="chat__messages" ref="messages">
<chat-message v-for="message in messages" :key="message.id" :message="message"></chat-message>
<button class="btn btn-primary form-control loadmorebutton" #click="handleButton">Load more</button>
</div>
export default{
data(){
return {
messages: [],
moreMessages: [],
moreMsgFetched: false
}
},
methods: {
removeMessage(id){...},
handleButton: function () {
if(!this.moreMsgFetched){
axios.get('chat/messagesmore').then((response) => {
this.moreMessages = response.data;
this.messages = this.moreMessages.splice(0, 10);
this.moreMsgFetched = true;
});
}
var nextMsgs = this.moreMessages.splice(0, 10);
//if you want to replace the messages array every time with 10 more messages
this.messages = nextMsgs
//if you wnt to add 10 more messages to messages array
this.messages.push(nextMsgs);
}
},
mounted(){
axios.get('chat/messages').then((response) => {
this.messages = response.data
});
Bus.$on('messages.added', (message) => {
this.messages.unshift(message);
//more code
}).$on('messages.removed', (message) => {
this.removeMessage(message.id);
});
}
}
-initialize a data property morMsgFetched set to false to indicate if more messages are fetched or not
if morMsgFetched is false make the axios request and st the response to moreMessages, then remove 10 from moreMessages and set it to messages[]..
After that set morMsgFetched to true
on subsequest click remove 10 from moreMessages and push it to 'messages[]`
Use Laravels built in pagination.
public function index()
{
return Message::with('user')->latest()->paginate(20);
}
It returns you next_page url which you can use to get more results calculated automatically
This might be too late but i believe the best way to do it is using pagination, Initially onMounted you'll send a request to let's say /posts?page=1, the one is a variable let's say named 'pageNumber', each time the user clicks on the "Load More" button, you'll increment the pageNumber and resent the request, the link will page /posts?page=2 this time, at this point you can append the results you've got to the already existing one and decide if the Load More button should be shown based on the last_page attribute returned by laravel paginator...
I'm sure you already solved your problem or found another alternative, this might be usefull for future developers.

Using Laravel eloquent calculate total of like and passing into vue js file

Currently i am implementing a like system into my laravel project with Vue js. The scenario is after users liked the post. It will showing the total like of the post beside the like button. If using controller and passing data into view is easy to be done. But when change to Vue js i have no idea how to do it. This is my Like.vue file.
<template>
<button class="btn btn-primary" v-if="!auth_user_likes_post" #click="like()">
Support
</button>
<button class="btn btn-primary" v-else #click="unlike()">
Unsupport
</button>
export default {
mounted(){
},
props: ['id'],
computed: {
likers() {
var likers = []
this.post.likes.forEach( (like) => {
likers.push(like.user.id)
})
return likers
},
auth_user_likes_post() {
var check_index = this.likers.indexOf(
this.$store.state.auth_user.id
)
if (check_index === -1)
return false
else
return true
},
post() {
return this.$store.state.posts.find( (post) => {
return post.id === this.id
})
}
},
methods: {
like() {
this.$http.get('/like/' + this.id)
.then( (resp) => {
this.$store.commit('update_post_likes', {
id: this.id,
like: resp.body
})
})
},
unlike() {
this.$http.get('/unlike/' + this.id)
.then( (response) => {
this.$store.commit('unlike_post', {
post_id: this.id,
like_id: response.body
})
})
}
}
}
The like and unlike functions has been done and working perfectly. Now i just need to show the total number.
This is Feed.vue file. The like was adding to this page.
<div class="post-description">
<p>{{ post.content }}</p>
<div class="stats">
<like :id="post.id"></like>
<a href="#" class="stat-item">
<i class="fa fa-retweet icon"></i>12
</a>
<a href="#" class="stat-item">
<i class="fa fa-comments-o icon"></i>3
</a>
</div>
</div>
If my function cannot be achieved the expected scenario then can you recommend other ways which can do that?
I have the returned array with likers. But at beginning i never though using this could be achieved my goal. So this {{ likers.length }} actually can show the total number.

Categories