I'm developing a live chat, and I have a problem that is as follows: There is a chat list with several conversations, and when I click on one of them, the component messages must make a request with the axios and put the messages on the screen, this already works today:
let CancelToken = axios.CancelToken;
let cancel;
export default {
data () {
return {
messages: [],
chatHiddenName: null,
chatId: null
}
},
mounted () {
EventBus.$on('CHAT_CLICKED', chat => {
console.log('chat clicked - chat message', chat)
this.messages = []
this.chatId = chat.id
this.chatHiddenName = chat.hidden_name
if (cancel !== undefined) {
cancel();
}
this.fetchMessages()
// this.chat = chat
})
},
methods: {
fetchMessages () {
console.log('FETCHING MESSAGES WITH CHAT ID', this.chatId)
axios.get(this.$parent.messagesendpoint, {
cancelToken: new CancelToken(function executor(c) {
// An executor function receives a cancel function as a parameter
cancel = c;
}),
params: {
chat_id: this.chatId,
page: 1,
count: 10,
}
}).then(response => {
// console.log(response)
let messages = []
// console.log(messages,this.chatHiddenName,chatId)
response.data.forEach(message => {
// add direct and color of message bubble
message.direction = {
// add offset if user message != of user chat
'offset-md-5': message.hidden_name !== this.chatHiddenName
}
message.color = {
'left': message.hidden_name === this.chatHiddenName,
'right': message.hidden_name !== this.chatHiddenName,
}
messages.push(message)
})
this.messages = messages
}).catch(error => {
console.log(error)
}).then(() => {
setTimeout(this.fetchMessages(), 500)
})
}
}
}
The problem I'm having is when I click on chat2, chat 1's request is still rolling and he keeps switching messages (he switches between chat1 and 2) for a while until he finishes all chat1 requests and keeps only I tried to do the axios cancel, but it is not working the way I wanted it, I want to cancel ALL the existing requests when CHAT_CLICKED is triggered