I try remove post from PostList, but getting an error
<PostList
:posts="sortedAndSearchedPosts"
#remove="removePost"
v-if="!isPostsLoading"
/>
remove post function
removePost(post) {
this.posts = this.posts.filter((p) => p.id !== post.id);
},
posts initialized here
computed: {
...mapState({
posts: (state) => state.post.posts,
}),
...mapGetters({
sortedPosts: "post/sortedPosts",
sortedAndSearchedPosts: "post/sortedAndSearchedPosts",
}),
},
Not clear where this.posts are actually initially set up.
If I guess your architecture right, I see 2 options for you:
either directly remove the post in your store so that sortedAndSearchedPosts reflects the change directly
if you don't want to update the global state, build a local copy when you initialise posts:
data () {
return {
posts: [...this.sortedAndSearchedPosts],
...
}
},
and update your code to use the local list of posts:
<PostList
:posts="posts"
...
/>
Hope this helps!
Related
I'm trying to clean up my warnings, but im facing those dependency warnings.
This is an example, but a lot of useEffect() is facing a similar problem.
Im trying to laod my page calling my fetch api inside useCallback (got samething inside useEffect), but the filter param there is actually a redux state
useEffect(() => {
if (checkValidRoute(env.activeSelector.menu, "indicacoes")) {
dispatch(
indicationsAction.getIndications(config.page, config.rowsPerPage, config.order, {
environmentId: env[router.query.ambiente].envId,
loginId: user.login?.id,
selectorID: env.activeSelector?.selectorID,
token: user.login.token,
details: false,
filter: {
status: config.status,
dateInit: dateFormat(beforeMonth),
dateEnd: dateFormat(today),
name: config.name,
indicatorName: config.indicatorName
}
})
)
} else {
router.push(`/${router.query.ambiente}`)
}
}, [env, config.status, config.order, dispatch, beforeMonth, config.indicatorName, config.name, config.page, config.rowsPerPage, router, today, user.login?.id, user.login.token])
Those filters has it value associated to an input, i do not want to re-fetch after change my config state, because i need to wait for the user fill all the filter fields, but i need to reload my page if my env change.
I thought about this solution, but it does not work
const filterParams = {
page: config.page,
rowsPerPage: config.rowsPerPage,
order: config.order,
details: false,
filter: {
status: config.status,
dateInit: dateFormat(beforeMonth),
dateEnd: dateFormat(today),
name: config.name,
indicatorName: config.indicatorName
}
}
const loadPage = useCallback(() => {
if (checkValidRoute(env.activeSelector.menu, "indicacoes")) {
dispatch(
indicationsAction.getIndications({
environmentId: env[router.query.ambiente].envId,
loginId: user.login?.id,
selectorID: env.activeSelector?.selectorID,
token: user.login.token,
}, filterParams)
)
} else {
router.push(`/${router.query.ambiente}`)
}
}, [dispatch, env, router, user.login?.id, user.login.token, filterParams])
useEffect(() => {
loadPage()
}, [loadPage])
Now I got the following warning:
The 'filterParams' object makes the dependencies of useCallback Hook (at line 112) change on every render. Move it inside the useCallback callback. Alternatively, wrap the initialization of 'filterParams' in its own useMemo() Hook.eslintreact-hooks/exhaustive-deps
if add filterParams to useMemo() dependencies samething will happend
// eslint-disable-next-line react-hooks/exhaustive-deps sounds not good ...
There's any solution for this ? I think that I have to change my form to useForm() to get the onChange values then after submit() i set my redux state... but i dont know yet
EDIT: In that case i did understand that we need differente states to control my input state and my request state, they cant be equals. If someone find another solution, i would appreciate (:
EDIT2: Solved by that way:
const [ filtersState ] = useState(
{
page: config.page,
rowsPerPage: config.rowsPerPage,
order: config.order,
data: {
environmentId: env[router.query.ambiente].envId,
loginId: user.login?.id,
selectorID: env.activeSelector?.selectorID,
token: user.login.token,
details: false,
filter: {
status: config.status,
dateInit: dateFormat(config.dateInit),
dateEnd: dateFormat(config.dateEnd),
name: config.name,
indicatorName: config.indicatorName
}
}
}
);
const handleLoadPage = useCallback(() => {
if (checkValidRoute(env.activeSelector.menu, "indicacoes")) {
dispatch(indicationsAction.getIndications({
...filtersState,
filters: {
...filtersState.filters,
selectorID: env.activeSelector?.selectorID,
}
}))
} else {
router.push(`/${router.query.ambiente}`)
}
}, [env.activeSelector, filtersState, dispatch, router]
)
useEffect(() => {
handleLoadPage()
}, [handleLoadPage])
Any other alternatives is appreciate
The thing here is, if you memoize something, it dependencies(if are in local scope) must be memoized too.
I recommend you read this amazing article about useMemo and useCallback hooks.
To solve your problem you need to wrap filterParams within useMemo hook. And if one of it dependencies are in local scope, for example the dateFormat function, you'll need to wrap it as well.
im really going through hard times trying to figure out how to get my API data through Vuex, is there some body whom has accurate bibliography of how to do this step by step, or even better help me with this code?
Formerly without using Vuex , but Vue all request worked perfectly, but now i dont understand clearly what i should do, here sharing part of my code:
data() {
return {
testArray: []
};
methods: {
getJsonData() {
fetch(
"https://app.ticketmaster.com/discovery/v2/events.json?countryCode=" +
this.countriesDrop +
"&apikey=xxxxxxxxxxxxxxxxxxxxxxxx",
{
method: "GET"
}
)
.then(response => {
return response.json();
})
.then(test => {console.log(this.testArray)
this.testArray = test._embedded.events;
})
.catch(err => {
console.log(err);
});
},
watch: {
countriesDrop: function(val) {
this.getJsonData();
}
},
As you can see in the request also is included an external element which make it changes attuning with the watcher and the value the user might asign.
I already got set Vuex and all else pluggins...just dont know how to act like , thus would appreciate an accurate link or tutorial either help with this basic problem resolved on detail step by step, .....thanks!
In your code there's nothing with Vuex. I guessed you want to set the state so that the getJsonData() method is called according to what's in the store.
Here's a snippet as an example of handling async in a Vuex environment.
const store = new Vuex.Store({
state: {
testArray: []
},
mutations: {
setTestArray(state, data) {
state.testArray = data
}
},
actions: {
getJsonData({
commit
}, countriesDrop) {
if (countriesDrop && countriesDrop !== '') {
fetch(`https://jsonplaceholder.typicode.com/${countriesDrop}`, {
method: "GET"
})
.then(response => {
return response.json();
})
.then(json => {
commit('setTestArray', json)
})
.catch(err => {
console.log(err);
});
}
}
}
})
new Vue({
el: "#app",
store,
computed: {
getDataFromStore() {
return this.$store.state.testArray
}
},
methods: {
getData(countriesDrop) {
this.$store.dispatch('getJsonData', countriesDrop)
}
}
})
<script src="https://cdn.jsdelivr.net/npm/es6-promise#4/dist/es6-promise.auto.js"></script>
<script src="https://unpkg.com/vuex#3.1.2/dist/vuex.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button #click="getData('todos')">GET TODOS</button>
<button #click="getData('albums')">GET ALBUMS</button>
<ol>
<li v-for="data in getDataFromStore">{{data.title}}</li>
</ol>
</div>
The point is that Vuex is a central element in a Vue-Vuex application. You can store app state, handle async and sync functions (actions, mutations) with it, and all your Vue components can rely on the state - that should be the "single source of truth".
So, you get your input from a component (the Vue instance in this snippet), and dispatch an action that is available in the Vuex store. If the action needs to modify the state, then you call a mutation to do that. With this flow you keep reactivity for all your components that use that state.
I used a computed to get data from the Vuex store, but getters can be set also.
This way you don't "pollute" your components with functions and data that should be in the store.
I'm trying to render my Guild component with data from Firestore. I put the data from Firestore into my state as an array, then when I call the component and try to render it, nothing shows. I want to believe I'm doing something very wrong here (haven't been working with React for very long), but I'm not getting any errors or warnings, so I'm not sure exactly what's happening.
Guilds.js
<Col>
<Card>
<CardBody>
<CardTitle className={this.props.guildFaction}>{this.props.guildName}</CardTitle>
<CardSubtitle>{this.props.guildServer}</CardSubtitle>
<CardText>{this.props.guildDesc}</CardText>
</CardBody>
</Card>
</Col>
Render function
renderCards() {
var guildComp = this.state.guilds.map(guild => {
console.log(guild)
return <Guilds
key={guild.id}
guildFaction={guild.guildFaction}
guildServer={guild.guildServer}
guildName={guild.guildName}
guildDesc={guild.guildDesc} />
})
return <CardDeck>{guildComp}</CardDeck>
}
Fetching Firestore Data
guildInfo() {
Fire.firestore().collection('guilds')
.get().then(snapshot => {
snapshot.forEach(doc => {
this.setState({
guilds: [{
id: doc.id,
guildDesc: doc.data().guildDesc,
guildFaction: doc.data().guildFaction,
guildName: doc.data().guildName,
guildRegion: doc.data().guildRegion,
guildServer: doc.data().guildServer
}]
})
console.log(doc.data().guildName)
})
})
}
UPDATE: solved, fix is in the render function.
Well, you using state "guilds" but you update state "posts" or I miss something?
I see few things here:
your component is Guild.js, but you are rendering <Guilds />
You are setting state to posts, but using this.state.guilds to render the components
You are overriding that piece of state each time to the last object in the snapshot, with the way you are mapping the Firestore data
you are setting the ids in the list wrong using doc.id instead of doc.data().id
You aren't mapping guilds to render. guilds is an array of guild objects, so you should do something like guilds.map(guild => { return <Guild /> }
These are few things to fix, and then try to console.log(this.state.guilds) before rendering and see if you get the right data
I think your issue is that because setState is async, by the time it actually sets the state doc is no longer defined. Try creating the array first, then call setState outside of the loop ie:
guildInfo() {
Fire.firestore().collection('guilds')
.get().then(snapshot => {
let guilds = []
snapshot.forEach(doc => {
guilds.push({
id: doc.id,
guildDesc: doc.data().guildDesc,
guildFaction: doc.data().guildFaction,
guildName: doc.data().guildName,
guildRegion: doc.data().guildRegion,
guildServer: doc.data().guildServer
});
})
this.setState({guilds});
})
}
Try to use a map function, and in the callback function of the setState, try to console log your state after the update:
guildInfo() {
Fire.firestore().collection('guilds')
.get()
.then(snapshot => {
const guilds = snapshot.map(doc => {
return {
id: doc.id,
guildDesc: doc.data().guildDesc,
guildFaction: doc.data().guildFaction,
guildName: doc.data().guildName,
guildRegion: doc.data().guildRegion,
guildServer: doc.data().guildServer
};
this.setState({guilds}, () => console.log(this.state))
})
})
})
}
If in the console log there's a little [i] symbol near your state, it means that the state is not ready, and therefore it's am async issue. Replacing the forEach with the map function may already help though.
I am trying to implement a vote button with vue js, when user click "Vote" will send axios request to server and store the data, then return json back. Same with unvote.
I also check if the user is voted, the button should change to Unvote like facebook.
So far the vote and unvote button is work correctly.
But i found a problems which is the voted features is not working. If user voted, after refresh page it will change back to "Vote", but it should be Unvote. But if the button was clicked, in database will showing the vote was deleted. Mean it should be problems of computed. But i am struggle on it since i not really know vue js.
This is my vue components.
<template>
<a href="#" v-if="isLiked" #click.prevent="unlike(comment)">
<span>UnVote</span>
</a>
<a href="#" v-else #click.prevent="like(comment)">
<span>Vote</span>
</a>
<script>
export default{
props: ['comment','liked'],
data: function() {
return {
isLiked: '',
}
},
mounted() {
axios.get('/comment/'+ this.comment.id +'/check', {})
.then((response) => {
this.liked = response.data;//here will get json "true" or "false"
});
this.isLiked = this.liked ? true : false;
},
computed: {
isLike() {
return this.liked;
},
},
methods: {
like(comment) {
axios.post('/comment/'+ comment.id +'/like')
.then(response => this.isLiked = true)
.catch(response => console.log(response.data));
},
unlike(comment) {
axios.post('/comment/'+ comment.id +'/unlike')
.then(response => this.isLiked = false)
.catch(response => console.log(response.data));
},
}
}
Your component instance does not have a liked data property and you should not attempt to set prop values (see https://v2.vuejs.org/v2/guide/components.html#One-Way-Data-Flow)
Also, you are attempting to set the isLiked value outside of the asynchronous operation which will not work how you think.
Just set the isLiked property...
mounted() {
axios.get('/comment/'+ this.comment.id +'/check', {})
.then((response) => {
this.isLiked = response.data; //here will get json "true" or "false"
});
},
Your isLike computed property is also never used.
I'm attempting to watch for localstorage:
Template:
<p>token - {{token}}</p>
Script:
computed: {
token() {
return localStorage.getItem('token');
}
}
But it doesn't change, when token changes. Only after refreshing the page.
Is there a way to solve this without using Vuex or state management?
localStorage is not reactive but I needed to "watch" it because my app uses localstorage and didn't want to re-write everything so here's what I did using CustomEvent.
I would dispatch a CustomEvent whenever you add something to storage
localStorage.setItem('foo-key', 'data to store')
window.dispatchEvent(new CustomEvent('foo-key-localstorage-changed', {
detail: {
storage: localStorage.getItem('foo-key')
}
}));
Then where ever you need to watch it do:
mounted() {
window.addEventListener('foo-key-localstorage-changed', (event) => {
this.data = event.detail.storage;
});
},
data() {
return {
data: null,
}
}
Sure thing! The best practice in my opinion is to use the getter / setter syntax to wrap the localstorage in.
Here is a working example:
HTML:
<div id="app">
{{token}}
<button #click="token++"> + </button>
</div>
JS:
new Vue({
el: '#app',
data: function() {
return {
get token() {
return localStorage.getItem('token') || 0;
},
set token(value) {
localStorage.setItem('token', value);
}
};
}
});
And a JSFiddle.
The VueJs site has a page about this.
https://v2.vuejs.org/v2/cookbook/client-side-storage.html
They provide an example.
Given this html template
<template>
<div id="app">
My name is <input v-model="name">
</div>
<template>
They provide this use of the lifecycle mounted method and a watcher.
const app = new Vue({
el: '#app',
data: {
name: ''
},
mounted() {
if (localStorage.name) {
this.name = localStorage.name;
}
},
watch: {
name(newName) {
localStorage.name = newName;
}
}
});
The mounted method assures you the name is set from local storage if it already exists, and the watcher allows your component to react whenever the name in local storage is modified. This works fine for when data in local storage is added or changed, but Vue will not react if someone wipes their local storage manually.
Update: vue-persistent-state is no longer maintained. Fork or look else where if it doesn't fit your bill as is.
If you want to avoid boilerplate (getter/setter-syntax), use vue-persistent-state to get reactive persistent state.
For example:
import persistentState from 'vue-persistent-state';
const initialState = {
token: '' // will get value from localStorage if found there
};
Vue.use(persistentState, initialState);
new Vue({
template: '<p>token - {{token}}</p>'
})
Now token is available as data in all components and Vue instances. Any changes to this.token will be stored in localStorage, and you can use this.token as you would in a vanilla Vue app.
The plugin is basically watcher and localStorage.set. You can read the code here. It
adds a mixin to make initialState available in all Vue instances, and
watches for changes and stores them.
Disclaimer: I'm the author of vue-persistent-state.
you can do it in two ways,
by using vue-ls and then adding the listener on storage keys, with
Vue.ls.on('token', callback)
or
this.$ls.on('token', callback)
by using storage event listener of DOM:
document.addEventListener('storage', storageListenerMethod);
LocalStorage or sessionStorage are not reactive. Thus you can't put a watcher on them. A solution would be to store value from a store state if you are using Vuex for example.
Ex:
SET_VALUE:(state,payload)=> {
state.value = payload
localStorage.setItem('name',state.value)
or
sessionStorage.setItem('name',state.value)
}