Unexpected behavior with watcher and axios response in vue - javascript

Today I came across an unexpected situation that I could solve, but I would like to understand what's happening.
I have a form for which I use a watcher to track any changes (deep).
If there are changes, another variable is set to true (so the form is dirty).
Typical use case where you warn users that they haven't saved their entries before they move away.
data() {
return {
formWatcher: null,
dirty: false,
form: {
id: '',
title: '',
content: '',
created_at: '',
updated_at: ''
}
}
},
...
watchForm() {
this.formWatcher = this.$watch('form', () => this.dirty = true, {deep: true})
},
unwatchForm() {
this.dirty = false
this.formWatcher()
},
...
async created() {
this.setData(...)
this.assignForm()
this.watchForm() // starts watching the form
},
So far, that works as expected.
If a user now saves his work by pressing the "update" button, We hit the server with a PUT, get the response, update the updated_at field (which is part of the form variable) and then we set dirty to false, avoiding further database calls.
First, my approach looked simple:
async update() {
let response = await axios.put(`/legals/${this.id}`, this.form)
let { updated_at } = response.data.data
this.form.updated_at = updated_at // this set dirty immediately to true
this.dirty = false // doesn't work, dirty is set immediately to true again
},
However, that didn't work - after the update, the dirty variable was immediately set to true again, because of this line:
this.form.updated_at = updated_at
Which lead me to the assumption that
this.dirty = false
runs before or asynchronous with
this.form.updated_at = updated_at
I then wrapped everything in the good old axios().then().then() way, and it worked as expected.
So finally I came up with this approach which worked as expected:
async update() {
let response = await axios.put(`/legals/${this.id}`, this.form)
let { updated_at } = response.data.data
await this.setFormAttribute('updated_at', updated_at)
await this.setDirty(false)
},
...
setFormAttribute(key, value) {
this.form[key] = value
},
setDirty(value) {
this.dirty = false
},
As you can see, I set the values now in setters functions, for which I "wait".
So, this works now exactly as I wanted, but I don't really understand why the naive approach didn't work.
I expected that if I wait for the response of axios in an async/await function, then assigning the respective variables would be synchronous, which however was not the case.
Can someone explain what's exactly going on here?

Related

Trigger cache to make sure data is right problem - swr hook - next.js ( with typescript )

In my next.js app i'm using the swr hook since it provides cache and real time updates, and that is quite great for my project ( facebook clone ), but, there's a problem.
The problem, is that, in my publications, i fetch them along with getStaticProps, and i just map the array and everything great, but, when i do an action, like, liking a post, or commenting a post, i mutate the cache, and i thought that what that does, is to ask the server if the information that is in the cache is right.
But, what it really does, is that, it makes another API call, and, the problem with that, is that, if i like a publication, after the call to the API to make sure everything is right in the cache, if there are 30 new publications, they will appear in the screen, and i don't want that, i want the pubs the user on screen requested at the beggining, imagine comenting on a post, then there are 50 new post so you lost the post where you commented...
Let me show you a litle bit of my code.
First, let me show you my posts interfaces
// Publication representation
export type theLikes = {
identifier: string;
};
export type theComment = {
_id?: string;
body: string;
name: string;
perfil?: string;
identifier: string;
createdAt: string;
likesComments?: theLikes[];
};
export interface Ipublication {
_id?: string;
body: string;
photo: string;
creator: {
name: string;
perfil?: string;
identifier: string;
};
likes?: theLikes[];
comments?: theComment[];
createdAt: string;
}
export type thePublication = {
data: Ipublication[];
};
This is where i'm making the call to get all posts
const PublicationsHome = ({ data: allPubs }) => {
// All pubs
const { data: Publications }: thePublication = useSWR(
`${process.env.URL}/api/publication`,
{
initialData: allPubs,
revalidateOnFocus: false
}
);
return (
<PublicationsHomeHero>
{/* Show pub */}
{Publications.map(publication => {
return <Pubs key={publication._id} publication={publication} />;
})}
</PublicationsHomeHero>
</>
);
};
export const getStaticProps: GetStaticProps = async () => {
const { data } = await axios.get(`${process.env.URL}/api/publication`);
return {
props: data
};
};
export default PublicationsHome;
And, for example, this is how i create a comment, i update cache, make the call to the API, then mutate to see if data is right
// Create comment
const handleSubmit = async (e: FormEvent<HTMLFormElement>): Promise<void> => {
e.preventDefault();
try {
mutate(
`${process.env.URL}/api/publication`,
(allPubs: Ipublication[]) => {
const currentPub = allPubs.find(f => f === publication);
const updatePub = allPubs.map(pub =>
pub._id === currentPub._id
? {
...currentPub,
comments: [
{
body: commentBody,
createdAt: new Date().toISOString(),
identifier: userAuth.user.id,
name: userAuth.user.name
},
...currentPub.comments
]
}
: pub
);
return updatePub;
},
false
);
await createComment(
{ identifier: userAuth.user.id, body: commentBody },
publication._id
);
mutate(`${process.env.URL}/api/publication`);
} catch (err) {
mutate(`${process.env.URL}/api/publication`);
}
};
Now, after creating the comment, as i already mentioned, it makes another call to the API, and if there are new posts or whatever, it will appear in the screen, and i just want to keep the posts i have or add new ones if i'm the one that created them.
So, let's say that i will like a post
Everything is great and fast, but, after making sure data is right, another post will appear because another user created it
Is there a way to make sure data is right without making another call to the API that will add more posts to the screen ?
I'm new to this swr hook, so, hope you can help me and thanks for your time !
Upate
There's a way to update cache without needing to refetch
many POST APIs will just return the updated data directly, so we don’t need to revalidate again. Here’s an example showing the “local mutate - request - update” usage:
mutate('/api/user', newUser, false) // use `false` to mutate without revalidation
mutate('/api/user', updateUser(newUser)) // `updateUser` is a Promise of the request,
// which returns the updated document
But, i don't kwow how should i change my code to implement this, any ideas !?
If you want to update the cache, and make sure everything is right, withouth having to make another call to the API, this seems like working
Change this
await createComment(
{ identifier: userAuth.user.id, body: commentBody },
publication._id
);
mutate(`${process.env.URL}/api/publication`);
For this
mutate(
`${process.env.URL}/api/publication`,
async (allPublications: Ipublication[]) => {
const { data } = await like(
{ identifier: userAuth.user.id },
publication._id
);
const updatePub = allPublications.map(pub =>
pub._id === data._id ? { ...data, likes: data.likes } : pub
);
return updatePub;
},
false
);
What you are doing there, is to update cache with the data that you'll receive data from the API's action, and you put it in the cache, but, you have to put false as well so it doesn't revalidate again, i tried it out and it's working, don't know if i'll have problems with it in the future, but for knowm it works great !

Handling dependent react queries

I have two react queries in the same component
const { data: sdrData, status: sdrDataLoading } = useQuery(
[queryInfo[0]?.dcsSysId, data[0]?.dcsStructSysId, data[cardIndex]?.dcsStructNodeId],
() => getSDR(queryInfo[0]?.dcsSysId, data[0]?.dcsStructSysId, data[cardIndex]?.dcsStructNodeId),
);
const { isIdle, data: sdrTemplateData, status: sdrTemplateDataLoading } = useQuery(
[sdrData[0]?.dcsSdrSysId, queryInfo[0]?.fldTemplateSysId],
() =>
SDRTemplateValues(sdrData[0]?.dcsSdrSysId, queryInfo[0]?.fldTemplateSysId, {
// The query will not execute until the userId exists
enabled: !!sdrData[0]?.dcsSdrSysId,
retry: true,
}),
);
My second query is depended on the first I need to access sdrData[0] for the first arg in my query however when I do this the query is undefined initially and it fails. Is there a good way to handle this. I saw you can set it equal to a variable, but I'm still faced with the same problem.
I need a way to tell the first query to wait until the second query is finished before it tried to access the arguments. I thought you could set enabled like I did, but that didn't work either.
I was able to solve this by adding the data parameter I need to the beginning of the argument array like this.
const { data: sdrData, status: sdrDataLoading } = useQuery(
queryInfo[0]?.dcsSysId && [
queryInfo[0]?.dcsSysId,
data[0]?.dcsStructSysId,
data[cardIndex]?.dcsStructNodeId,
],
() => getSDR(queryInfo[0]?.dcsSysId, data[0]?.dcsStructSysId, data[cardIndex]?.dcsStructNodeId),
);
const { data: sdrTemplateData, status: sdrTemplateDataLoading } = useQuery(
sdrData?.[0]?.dcsSdrSysId && [sdrData?.[0]?.dcsSdrSysId, queryInfo[0]?.fldTemplateSysId],
() => SDRTemplateValues(sdrData?.[0]?.dcsSdrSysId, queryInfo[0]?.fldTemplateSysId),
);
You are on the right path here.
You just need to check if sdrData is undefined. You are trying to access the first element (sdrData[0]) but initially it's undefined.
...
{
enabled: !!(sdrData && sdrData[0]?.dcsSdrSysId
}
...

React Hooks: Handling Objects as dependency in useEffects

UPDATE: Yes for use case 1, if I extract search.value outside the useEffect and use it as a dependency it works.
But I have an updated Use case below
Use Case 2: I want to pass a searchHits Object to the server. The server in turn return it back to me with an updated value in response.
If I try using the searchHits Object I still get the infinite loop
state: {
visible: true,
loading: false,
search: {
value: “”,
searchHits: {....},
highlight: false,
}
}
let val = search.value
let hits = search.searchHits
useEffect( () => {
axios.post(`/search=${state.search.value}`, {hits: hits}).then( resp => {
…do something or ..do nothing
state.setState( prevState => {
return {
…prevState,
search: {... prevState.search, hits: resp.hit}
}
})
})
}, [val, hits])
Use Case 1: I want to search for a string and then highlight when I get results
e.g.
state: {
visible: true,
loading: false,
search: {
value: “”,
highlight: false,
}
}
useEffect( () => {
axios.get(`/search=${state.search.value}`).then( resp => {
…do something or ..do nothing
state.setState( prevState => {
return {
…prevState,
search: {... prevState.search, highlight: true}
}
})
})
}, [state.search])
In useEffect I make the API call using search.value.
eslint complains that there is a dependency on state.search , it does not recognize state.search.value. Even if you pass state.search.value it complains about state.search
Now if you pass state.search as dependecy it goes in an infinite loop because after the api call we are updating the highlights flag inside search.
Which will trigger another state update and a recursive loop.
One way to avoid this is to not have nested Objects in state or move the highlights flag outside search, but I am trying to not go that route give the sheer dependecies I have.
I would rather have an Object in state called search the way it is. Is there any way to better approach this.
If I want to keep my state Object as above how do I handle the infinite loop
Just a eslint stuff bug may be. You have retracted some code by saying //do something and have hidden he code. Are you sure that it doesn't have anything to do with search object?
Also, try to extract the variable out before useEffect().
const searchValue = state.search.value;
useEffect(()=>{// axios call here},[searchValue])
If your search value is an object, react does shallow comparison and it might not give desired result. Re-rendering on a set of object dependencies isn't ideal. Extract the variables.
React does shallow comparison of dependencies specified in useEffect
eg.,
const {searchParam1, searchParam2} = search.value;
useEffect(() => {
//logic goes here
}, [searchParam1, searchParam2]);
Additionally, you can add dev dependency for eslint-plugin-react-hooks, to identify common errors with hooks

Reference to javascript object apparently returning different values in different places with no modifications in between

I'm using a variable twice within a function but it returns different values even though I'm making no modifications to it.
This is happening within a form component developed with Vue.js (v2) which dispatches a Vuex action. I think this has nothing to do with Vue/Vuex per se, but it's important to understand part of the code.
Here is the relevant piece of code from my component
import { mapActions } from 'vuex'
export default {
data() {
return {
product: {
code: '',
description: '',
type: '',
productImage: [],
productDocs: {},
}
}
},
methods: {
...mapActions(['event']),
save() {
console.log("this.product:", this.product)
const valid = this.$refs.form.validate() // this validates the form
console.log("this.product:", this.product)
if (valid) {
try {
this.event({
action: 'product/addProduct',
data: this.product
})
}
finally {
this.close()
}
}
},
// other stuff
and a small piece of code for the vuex action "event"
event: async ({ dispatch }, event) => {
const time = new Date()
const evid = `${Date.now()}|${Math.floor(Math.random()*1000)}`
console.log(`Preparing to dispatch... Action: ${event.action} | data: ${JSON.stringify(event.data)} | Event ID: ${evid}`)
// enriching event
event.evid = evid;
event.timestamp = time;
event.synced = 0
// Push user event to buffer
try {
await buffer.events.add(event)
} catch (e) {
console.log(`Error writing event into buffer. Action ${event.action} | evid: ${evid} `)
}
// dispatch action
try {
await dispatch(event.action, event)
}
catch (err) {
console.log(`Error dispatching action: ${event.action} | data: ${event.data}\n${err.stack || err}`)
window.alert('Could not save. Try again. \n' + err + `\n Action: ${event.action} | data: ${event.data}`)
}
},
The problem is with this.product. I've placed the several console.log to check out the actual values because it wasn't working as expected. The logs from the save() functions return undefined, but within the event function (a vuex action) the values are as expected, as shown in the console logs:
When I log this.product in the save() function. Both logs are the same.
When I log the event in the vuex action, it shows that event.data is actually the product.
I must be doing something terribly wrong here, but I'm totally blind to it. Any help is appreciated.
#Sumurai8: thanks for editing the question and for the hint.
Part of this may be because of that tiny i next to the opened product.
If you hover over it, it says that "the object has been evaluated just
now", which means it evaluates what is in the object when you open the
object, which is way after executing the action. [...] Whatever is
changing the product may very well happen after the event somewhere.
It actually helped me find the solution.
Basically within the this.close function called in the finally statement of the save() function, I was resetting the form and thus this.product, which was used solely to hold the form data. So at evaluation time, the object had undefined properties, while the event function managed to output to the console before the reset. However at the end the store would not get updated as expected (that's how I noticed the issue), because the event function and the action called within it are asynchronous and so the value got reset before the actual mutation of the vuex store.
Logging JSON.stringify(this.product) outputted the right value even within the save() method. I used that to create a more robust copy of the data and passed that to the event function as follows:
this.event({
action: 'product/addProduct',
data: JSON.parse(JSON.stringify(this.product))
})
Now everything works like a charme.

Meteor - How to find out if Meteor.user() can be used without raising an error?

I'm looking for a way to determine if Meteor.user() is set in a function that can be called both from the server and client side, without raising an error when it is not.
In my specific case I use Meteor server's startup function to create some dummy data if none is set. Furthermore I use the Collection2-package's autoValue -functions to create some default attributes based on the currently logged in user's profile, if they are available.
So I have this in server-only code:
Meteor.startup(function() {
if (Tags.find().fetch().length === 0) {
Tags.insert({name: "Default tag"});
}
});
And in Tags-collection's schema:
creatorName: {
type: String,
optional: true,
autoValue: function() {
if (Meteor.user() && Meteor.user().profile.name)
return Meteor.user().profile.name;
return undefined;
}
}
Now when starting the server, if no tags exist, an error is thrown: Meteor.userId can only be invoked in method calls. Use this.userId in publish functions.
So in other words calling Meteor.user() on the server startup throws an error instead of returning undefined or null or something. Is there a way to determine whether it will do so prior to calling it?
I cannot solve this simply by wrapping the call with if (Meteor.isServer) within the autoValue function, as the autoValue functions are normally called from server side even when invoked by the user, and in these cases everything in my code works fine.
Note that this is related to How to get Meteor.user() to return on the server side?, but that does not address checking if Meteor.user() is available in cases where calling it might or might not result in an error.
On the server, Meteor.users can only be invoked within the context of a method. So it makes sense that it won't work in Meteor.startup. The warning message is, unfortunately, not very helpful. You have two options:
try/catch
You can modify your autoValue to catch the error if it's called from the wrong context:
autoValue: function() {
try {
var name = Meteor.user().profile.name;
return name;
} catch (_error) {
return undefined;
}
}
I suppose this makes sense if undefined is an acceptable name in your dummy data.
Skip generating automatic values
Because you know this autoValue will always fail (and even if it didn't, it won't add a useful value), you could skip generating automatic values for those inserts. If you need a real name for the creator, you could pick a random value from your existing database (assuming you had already populated some users).
Been stuck with this for two days, this is what finally got mine working:
Solution: Use a server-side session to get the userId to prevent
"Meteor.userId can only be invoked in method calls. Use this.userId in publish functions."
error since using this.userId returns null.
lib/schemas/schema_doc.js
//automatically appended to other schemas to prevent repetition
Schemas.Doc = new SimpleSchema({
createdBy: {
type: String,
autoValue: function () {
var userId = '';
try {
userId = Meteor.userId();
} catch (error) {
if (is.existy(ServerSession.get('documentOwner'))) {
userId = ServerSession.get('documentOwner');
} else {
userId = 'undefined';
}
}
if (this.isInsert) {
return userId;
} else if (this.isUpsert) {
return {$setOnInsert: userId};
} else {
this.unset();
}
},
denyUpdate: true
},
// Force value to be current date (on server) upon insert
// and prevent updates thereafter.
createdAt: {
type: Date,
autoValue: function () {
if (this.isInsert) {
return new Date;
} else if (this.isUpsert) {
return {$setOnInsert: new Date};
} else {
this.unset();
}
},
denyUpdate: true
},
//other fields here...
});
server/methods.js
Meteor.methods({
createPlant: function () {
ServerSession.set('documentOwner', documentOwner);
var insertFieldOptions = {
'name' : name,
'type' : type
};
Plants.insert(insertFieldOptions);
},
//other methods here...
});
Note that I'm using the ff:
https://github.com/matteodem/meteor-server-session/ (for
ServerSession)
http://arasatasaygin.github.io/is.js/ (for is.existy)

Categories