"Remount" a method in vue js component - javascript

i'm not so well-versed in Vue.js or frontend so maybe what I'm trying to achieve is not the right approach, but here's my situation:
mounted() {
this.newMessages();
this.scrollDown();
},
updated() {
// prop gets updated from parent component, newMessages method depends on it
this.$options.mounted = [
this.newMessages(),
];
this.scrollDown();
},
methods: {
newMessages() {
// logic, uses prop thread.id passed to component, needs to be initiated on mount
},
scrollDown() {
// logic
},
},
The question is: How to I "remount" a method in Vue.js mounted hook component, if the updated hook fires?
Now, here's what happening, newMessages method get's a broadcast over websockets. It uses a prop called thread (id property of that object) to listen on specific channel.
Now when parent component changes that prop (thread) the DOM of the component changes to show messages from that thread, but that listener method still listens on a wrong channel.
I tried $options to reset mounted hook, but that only stacks the method mounted, and gets the same message multiple times.

Related

Vue.js component method on creation

I'm new to Vue and I'd like to make an AJAX call every time my component is rendered.
I have a vue component lets say "test-table" and Id like to fetch the contents via an AJAX call. There are many such tables and I track the active one via an v-if/v-else-if etc.
Currently I have a cheaty solution: in the template for the component I call a computed property called getData via {{ getData }} which initiates the Ajax call but does only return an empty string. Id like to switch to the proper way but dont know how.
My code is like so: (its typescript)
Vue.component("test-table", {
props: ["request"],
data () {
return {
tableData: [] as Array<TableClass>,
}
},
template: `{{ getData() }} DO SOME STUFF WITH tableData...`,
computed: {
getData() : string {
get("./foo.php", this.request, true).then(
data => this.tableData = data.map(element => new TableClass(data))
)
return "";
}
}
}
HTML:
<test-table v-if="testcounter === 1" :request="stuff...">
<test-table v-else-if="testcounter === 2" :request="other stuff...">
...
get is an async method that just sends a GET request with request data to the server. The last parameter is only for saying the method to expect a JSON as answer. Similar to JQuerys getJSON method.
the "created" method does NOT work! It fires only one time when the component is first created. If I deactivate and activate again (with v-if) the method is not called again.
Btw: I'm using Vue 2.6.13
Lifecycle hooks won't fire every time if the component is cached, keep-alive etc
Add a console.log in each of the lifecycle hooks to see.
Change to use a watcher which handles firing getData again if request changes.
...
watch: {
request: {
handler: function() {
this.getData()
},
deep: true
}
},
created() {
this.getData()
},
methods: {
getData(): string {
// do request
}
}
#FlorianBecker try the lifecycle hook updated(). It may be a better fit for what you're trying to achieve. Docs here.
You should be able to use the mounted hook if your component is continuously rendered/unrendered using v-if, like so:
export default {
mounted() {
// do ajax call here
this.callAMethod();
},
...
}
Alternatively, you could use the created() hook but it is executed earlier in the chain, so this means the DOM template is not created yet so you cant refer to it. mounted usually is the way to go.
More info on these hooks can be found here.

Vue Router - call function after route has loaded

I'm working on a project where I need to call a function AFTER the route has finished loading. However, when using the 'watch' functionality, it only loads on route change, but does so before route has finished loading. So when I attempt to run a script that targets DOM elements on the page, those elements don't exist yet. Is there any functionality in Vue Router that would allow me to wait until everything is rendered before running the script?
const app = new Vue({
el: '#app',
router,
watch: {
'$route': function (from, to) {
function SOMEFUNCTION()
}
},
data: {
some data
},
template: `
<router-view/>
`
})
You should use Vue.nextTick
In your case this would translate to:
const app = new Vue({
el: '#app',
router,
watch: {
$route() {
this.$nextTick(this.routeLoaded);
}
},
data() {
return {};
},
methods: {
routeLoaded() {
//Dom for the current route is loaded
}
},
mounted() {
/* The route will not be ready in the mounted hook if it's component is async
so we use $router.onReady to make sure it is.
it will fire right away if the router was already loaded, so catches all the cases.
Just understand that the watcher will also trigger in the case of an async component on mount
because the $route will change and the function will be called twice in this case,
it can easily be worked around with a local variable if necessary
*/
this.$router.onReady(() => this.routeLoaded());
},
template: `<router-view/>`
})
This will call the routeLoaded method every time the route changes (which I'm deducing is what you need since you are using the <router-view> element), if you also want to call it initially, I would recommend the mounted hook (like in the example) or the immediate flag on the watcher
In my opinion on this situation, you should use component life cycle method of the loaded component, either use mounted method or created method.
or if your script doesn't depend on any vue component (store) you can use router.afterEach hook
router.afterEach((to, from) => { if (to.name !== 'ROUTENAME'){ // do something }});
The solution for me was to set up a custom event in every page's mounted() hook with a mixin and listen for that event on the body for example. If you wanted to strictly tie it with the router's afterEach or the route watcher to ensure the route has indeed changed before the event was fired, you could probably set up a Promise in the afterEach and resolve it in the page's mounted() by either the event or sharing the resolve function through the window.
An example:
// Component.vue
watch: {
'$route': function (from, to) {
new Promise((resolve) => {
window.resolveRouteChange = resolve;
}).then(() => {
// route changed and page DOM mounted!
});
}
}
// PageComponent.vue
mounted() {
if(window.resolveRouteChange) {
window.resolveRouteChange();
window.resolveRouteChange = null;
}
}
In case of router-view, we can manually detect router-view.$el change after $route is changed
watch: {
'$route'(to, from) {
// Get $el that is our starting point
let start_el = this.$refs.routerview.$el
this.$nextTick(async function() { await this.wait_component_change(start_el)})
}
},
methods: {
on_router_view_component_changed: function() { }
wait_component_change: async function(start_el) {
// Just need to wait when $el is changed in async manner
for (let i = 0; i < 9; i++) {
console.log('calc_has_dragscroll ' + i)
if(start_el) {
if (!start_el.isSameNode(this.$refs.routerview.$el)) {
// $el changed - out goal completed
this.on_router_view_component_changed()
return
}
}
else {
// No start_el, just wait any other
if(this.$refs.routerview.$el) {
// $el changed - out goal completed too
this.on_router_view_component_changed()
return
}
}
await this.$nextTick()
}
},
}
You can accomplish this by hooking into VueJS lifecycle hooks:
Use VueJS Lifecycle Hooks:
Here is a summary of the major VueJS lifecycle hooks. Please consult the documentation for the full description.
i. beforeCreate: This function will be called before the component is created
ii. created: This function will be called after the component is created, but note although the component is created, it hasn't been mounted yet. So you won't be able to access the this of the component. However, this is a good place to make Network Requests that will update the data properties.
iii. mounted: This function is called once the component has been rendered and the elements can be accessed here. This is what you're looking for.
iv. beforeDestroy: This function is called before the component is destroyed. This can be useful to stop any listeners (setTimeout, setInterval..), that you created.
See the diagram below for the details.
const app = new Vue({
el: '#app',
router,
mounted(){
this.someFunction()
},
data: {
some data
},
template: `
<router-view/>
`
})
Use Vue Router Navigation Guards: Vue Router also expose some lifecycle hooks that can you hook into. However, as you will see below they do not fit your requirements:
i. beforeRouteEnter: called before the route that renders this component is confirmed. oes NOT have access to this component instance, because it has not been created yet when this guard is called!
ii. beforeRouteUpdate: called when the route that renders this component has changed, but this component is reused in the new route.
iii. beforeRouteLeave: called when the route that renders this component is about to be navigated away from.
References:
VueJS Documentation (LifeCycle): VueJS Instance
Vue Router Documentation (Navigation Guards): Navigation Guards

react-native componentDidMount to fetch from server

constructor(props) {
super(props);
console.log("props");
this.state = {
userId : "12345",
};
}
componentDidMount() {
console.log("componentDidMount");
Actions.getProductDetails({userId:"123456"});
Actions.getProductDetails.completed.listen(this.gotProductDetails.bind(this));
Actions.cancelOrder.completed.listen(this.cancelOrderCompleted.bind(this));
}
gotProductDetails(data) {
console.log("gotProductDetails");
}
goBack(data) {
console.log("justgoback");
this.props.back();
}
cancelProduct() {
console.log("SDsadsadsad");
Actions.cancelOrder({
orderId:this.state.order.id,
canelMsg:this.state.selectedReason,
userId:this.state.userId
});
}
cancelOrderCompleted(data) {
console.log("cancelOrderCompleted");
this.goBack();
}
My issue is some functions are mounting twice whenever I change the
route and revisit this route again I would show you console.log here
This is for first time I come to this route:
props
cancelOrder.js:190 componentDidMount
cancelOrder.js:197 gotProductDetails
Now I will do cancelProduct call and log will be
SDsadsadsad
cancelOrder.js:221 cancelOrderCompleted
cancelOrder.js:210 justgoback
This is for second time i.e, I will go back from this route and revisit:
props
cancelOrder.js:190 componentDidMount
cancelOrder.js:197 gotProductDetails
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the cancelOrder component.
cancelOrder.js:197 gotProductDetails
Now I will do cancelProduct call and log will be
SDsadsadsad
cancelOrder.js:221 cancelOrderCompleted
cancelOrder.js:210 justgoback
cancelOrder.js:221 cancelOrderCompleted
cancelOrder.js:210 justgoback
In the above log you can see that for the second time line number 197 221 210 executed twice with the error I was not able to solve
I'm using react navigator for route
I checked in release version also, but it is having same error it was told in one Github issue, but was not able to find now.
Every time you run this line
Actions.cancelOrder.completed.listen(this.cancelOrderCompleted.bind(this));
The listen method gets a new function instance every time it runs, so if this page was mounted twice in the app's lifecycle, the cancelOrderCompleted would run twice and one of them probably in an unmounted component which is bad.
Generally I would advise that your getProductDetails would return a Promise. If you don't want to do that, make sure you remove the listeners when your component is unmounted.
And be aware that cancelOrderCompleted.bind(this) creates a new delegate instance that you can't recreate when stopping the listener. Unless you keep it in a data member.
Edit:
Code example -
constructor(props) {
super(props);
console.log("props");
this.state={
userId : "12345",
}
this.getProductDetailsBound = this.gotProductDetails.bind(this);
this.cancelOrderCompletedBound = this.cancelOrderCompleted.bind(this);
}
componentDidMount() {
console.log("componentDidMount")
// Listen before you call getProductDetails, not after
Actions.getProductDetails.completed.listen(this.getProductDetailsBound);
Actions.cancelOrder.completed.listen(this.cancelOrderCompletedBound);
Actions.getProductDetails({userId:"123456"});
}
componentWillUnmount() {
Actions.getProductDetails.completed.stopListening(this.getProductDetailsBound);
Actions.cancelOrder.completed.stopListening(this.cancelOrderCompletedBound);
}

react-redux store not updating within onClick function

I'm experiencing this weird issue where my react-redux store is updating, but is not updating within the function that calls the actions.
this.props.active is undefined, then I set it to an integer with this.props.actions.activeSet(activeProc), but it remains undefined and enters the next if condition.
I know my app is working because everything else works with this.props.active having the correct value.
Is this supposed to happen?
edit:
After doing some testing, it appears that the state remains the same inside the onClick function.
All calls to console.log(this.props) made within the onClick function show no change to the state, but adding setTimeout(() => {console.log(this.props)}, 1) at the end to test shows that the state is being updated.
Other parts of the app are working as intended, with state changes applied immediately.
But I still don't understand what is going on.
Component function code
() => {
console.log(this.props.active); // undefined
if (this.props.active === undefined && this.props.readyQueue.length > 0) {
let activeProc = this.props.readyQueue[0];
this.props.actions.readyPop();
this.props.actions.activeSet(activeProc); // set to an integer
this.props.actions.execStateSet("Running");
}
console.log(this.props.active); // still remains undefined
if (this.props.active === undefined) {
this.props.actions.execStateSet("Idle");
}
}
function mapStateToProps(state, props) {
return {
active: state.ProcessReducer.active,
};
}
Action code
export const activeSet = (procId) => {
return {
type: 'ACTIVE_SET',
procId
}
}
Reducer code
case 'ACTIVE_SET':
return Object.assign({}, state, {
active: action.procId
});
Your Redux state updates synchronously with the dispatch of your action. Your reducer has executed by the time the dispatch call returns.
However, React isn't Redux. Redux tells React-Redux's wrapper component that the state has changed. This also happens before dispatch returns.
React-Redux then tells React that the component needs to be rerendered by calling forceUpdate. React then waits until it feels it's a good time to take care of that. I haven't looked, but it probably uses setImmediate or equivalent but it's async. This allows React to batch updates and maybe there are other reasons.
In any case, the React-Redux wrapper component will get rendered by React when the time comes and it'll use your mapStateToProps to distill theprops out of the state and then passes them to React as props for your actual component. Then, when React feels it's an okay time, it calls your render method or function. It may do all kinds of things in before that, such as calling componentWillReceiveProps or rendering some other component that also needs rendering. In any case it's none of our business. React does its thing. But when your Render function is called, your props will now reflect the new state.
You shouldn't rely on new state in an onClick handler. The onClick should only call the bound action creator, which I guess is now more aptly called an action dispatcher. If something needs to be done with the new state, you should use Redux-Thunk middleware and create a thunked action creator. These have access to getState and if they don't perform any internal async stuff, then the entire action can actually be just as synchronous as a simple dispatch (not that you'd need that in a simple onClick handler).
Finally, React is very asynchronous in nature. Think of it as telling React what you want (component + props) and letting React take it from there. If React needs to know how to turn a component into DOM elements, it'll call your component's render function. How or when React does is thing is an implementation detail that doesn't concern us.

React mqtt subscription setState warning

I'm using https://www.npmjs.com/package/mqtt with React. In my component I have:
componentDidMount:function(){
client.subscribe('test/topic');
client.on('message',function(topic,message){
if(topic==='test/topic'){
console.log(message.toString());
this.setState({value:parseInt(message.toString())});
}
}.bind(this));
},
componentWillUnmount:function(){
client.unsubscribe('test/topic');
},
So I subscribe to the topic when component will mount and unsubscribe when it unmounts. However, when i go to another view in my app and come back i get a warning with every mqtt message:
Warning: setState(...): Can only update a mounted or mounting component.
This usually means you called setState() on an unmounted component.
This is a no-op.
What am i doing wrong?
I had similar issues at one point. I have since moved back to the older useEffect syntax for my socket listeners and I don't seem to get those warnings now. Not certain that this is the fix but hopefully it helps!
useEffect(() => {
client.on('message' () => {
// update state
}
client.on('disconnect', () => {
// update state
}
})
The callback function is getting called when the didMount method is declared. Move the callback into its own method. You won't need to bind this, either.

Categories

Resources