How to use settimeout with vue.js watchers? - javascript

I have custom watcher for search field in my application:
watch: {
search (query) {
if(query.length > 2) {
axios.post(url, query)
.then(res => {
console.log(res)
})
.catch(error => {
console.log(error)
})
}
}
}
Here as you see I've send request to server on everey change value of search var in my case. I tired paste my code inside setTimeout but when user typing 3 time then requests too sent 3 times instead of one time. I need to wait when user is typing and after stop typing send one request to server.
setTimeout(function () {
// request code here
}, 3000);
How I can do it correctly inside vue.js watchers?

You can use debounce in lodash. It's perfect for your usecase.
import _ from lodash
watch: {
search (query) {
this.performSearch(query)
}
},
methods: {
performSearch: _.debounce(function(query) {
axios.post(url, query)
.then(res => {
console.log(res)
})
.catch(error => {
console.log(error)
})
}, 200)
}
If you want to implement it without lodash library, you can try
data() {
return {
timeoutQuery: null
}
},
watch: {
search (query) {
if (this.timeoutQuery) { clearTimeout(this.timeoutQuery) }
this.timeoutQuery = setTimeout(this.performSearch(query), 300)
}
},
methods: {
performSearch(query) {
axios.post(url, query)
.then(res => {
console.log(res)
})
.catch(error => {
console.log(error)
})
}
}

You should use any flag to indicate than your request is busy:
data () {
return {
isRequestBusy: false
}
},
watch: {
search (query) {
if(query.length > 2 && !this.isRequestBusy) {
this.isRequestBusy = true
axios.post(url, query)
.then(res => {
console.log(res)
})
.catch(error => {
console.log(error)
})
.finally(() => {
this.isRequestBusy = false
})
}
}
}

You can use the arrow function and put your code inside of it.
data() {
return {
query: "",
queryTimeout: null
};
},
watch: {
query(newValue, oldValue) {
console.log(newValue, oldValue);
const timer = 500; // In miliseconds
if (this.queryTimeout) {
clearTimeout(this.queryTimeout);
}
setTimeout(() => {
this.fetchData(newValue)
}, timer);
}
},
methods: {
fetchData(query = null) {
console.log(query);
// Put your logic code here
}
}
For more way to solve this problem, check this link.
https://stackoverflow.com/a/38431406/4494207

Related

Get source in constructor

I'm trying to make a search with autocomplete, tell me how I can get in the constructor an array of label and results with axios get
new Autocomplete(input, {
source: (response) => {
axios.get('{{ route('api.autocomplete) }}', {
params: {
term: input.value
}
})
.then(response => {
return {
label: response.data.name,
results: response.data.children,
}
})
},
select: ({element}) => {
alert(element);
}
});
class Autocomplete {
constructor(element, {
source = () => {},
select = () => {},
}) {
console.log(source);
}
}
Instead of an array, it gives out a piece of axios request code

Vuex: Wait for websocket response before dispatching action

So this is the scenario / premises:
In order to populate a chat queue in real time I need to open a connection to a websocket, send a message and then set the data to a websocket store. This store will basically manage all the websocket state.
Before populating the chat queue there's two parameters I need: a shiftId coming from one http API request and a connectionId coming from the websocket. Using those two parameters I finally can subscribe to a third http API and start receiving messages to populate the chat queue.
The problem is that due to the async behaviour of the websocket (or that's what I think, please feel to correct me if I'm wrong) I always get an empty "connectionId" when trying to make the put to that "subscription" API. I have tried with async/await and promises but nothing seems to work. I'm pretty new to async/await and websockets with Vuex so pretty sure I'm doing something wrong.
This is the user vuex module where I do all the login/token operations and dispatch a "updateEventsSubscription" action from the shift vuex module. In order for the "updateEventsSubscription" action to work I need to get the response from the "processWebsocket" action (to get the connectionId parameter) and from the "startShift" action (to get the shiftId parameter) coming from the shifts vuex module:
import UserService from '#/services/UserService.js'
import TokenService from '#/services/TokenService.js'
import router from '#/router'
export const namespaced = true
export const state = {
accessToken: '',
errorMessage: '',
errorState: false,
userEmail: localStorage.getItem('userEmail'),
userPassword: localStorage.getItem('userPassword'),
}
export const mutations = {
SET_TOKEN(state, accessToken) {
state.accessToken = accessToken
TokenService.saveToken(accessToken)
},
SET_USER(state, authUserJson) {
state.userEmail = authUserJson.email
state.userPassword = authUserJson.password
localStorage.setItem('userPassword', authUserJson.password)
localStorage.setItem('userEmail', authUserJson.email)
},
SET_ERROR(state, error) {
state.errorState = true
state.errorMessage = error.data.error_description
},
CLOSE_NOTIFICATION(state, newErrorState) {
state.errorState = newErrorState
},
}
export const actions = {
signIn({ commit, dispatch, rootState }, authUserJson) {
return UserService.authUser(authUserJson)
.then((result) => {
commit('SET_USER', authUserJson)
commit('SET_TOKEN', result.data.access_token)
dispatch('token/decodeToken', result.data.access_token, {
root: true,
})
dispatch(
'shifts/updateEventsSubscription',
rootState.token.agentId,
{
root: true,
}
)
router.push('/support')
})
.catch((error) => {
console.log(error)
if (error.response.status === 400) {
commit('SET_TOKEN', null)
commit('SET_USER', {})
commit('SET_ERROR', error.response)
} else {
console.log(error.response)
}
})
},
signOut({ commit }) {
commit('SET_TOKEN', null)
commit('SET_USER', {})
localStorage.removeItem('userPassword')
localStorage.removeItem('userEmail')
TokenService.removeToken()
router.push('/')
},
closeNotification({ commit }, newErrorState) {
commit('CLOSE_NOTIFICATION', newErrorState)
},
}
export const getters = {
getToken: (state) => {
return state.accessToken
},
errorState: (state) => {
return state.errorState
},
errorMessage: (state) => {
return state.errorMessage
},
isAuthenticated: (state) => {
return state.accessToken
},
userEmail: (state) => {
return state.userEmail
},
userPassword: (state) => {
return state.userPassword
},
}
This is websocket store: I pass the connectionId to the state in order to be able to use it in another vuex action to subscribe for new chats:
export const namespaced = true
export const state = {
connected: false,
error: null,
connectionId: '',
statusCode: '',
incomingChatInfo: [],
remoteMessage: [],
messageType: '',
ws: null,
}
export const actions = {
processWebsocket({ commit }) {
const v = this
this.ws = new WebSocket('mywebsocket')
this.ws.onopen = function (event) {
commit('SET_CONNECTION', event.type)
v.ws.send('message')
}
this.ws.onmessage = function (event) {
commit('SET_REMOTE_DATA', event)
}
this.ws.onerror = function (event) {
console.log('webSocket: on error: ', event)
}
this.ws.onclose = function (event) {
console.log('webSocket: on close: ', event)
commit('SET_CONNECTION')
ws = null
setTimeout(startWebsocket, 5000)
}
},
}
export const mutations = {
SET_REMOTE_DATA(state, remoteData) {
const wsData = JSON.parse(remoteData.data)
if (wsData.connectionId) {
state.connectionId = wsData.connectionId
console.log(`Retrieving Connection ID ${state.connectionId}`)
} else {
console.log(`We got chats !!`)
state.messageType = wsData.type
state.incomingChatInfo = wsData.documents
}
},
SET_CONNECTION(state, message) {
if (message == 'open') {
state.connected = true
} else state.connected = false
},
SET_ERROR(state, error) {
state.error = error
},
}
And finally this is the shift store (where the problem is), as you can see I have a startShift action (everything works fine with it) and then the "updateEventsSubscription" where I'm trying to wait for the response from the "startShift" action and the "processWebsocket" action. Debugging the app I realize that everything works fine with the startShift action but the websocket action sends the response after the "updateEventsSubscription" needs it causing an error when I try to make a put to that API (because it needs the connectionId parameter coming from the state of the websocket).
import ShiftService from '#/services/ShiftService.js'
export const namespaced = true
export const state = {
connectionId: '',
shiftId: '',
agentShiftInfo: '{}',
}
export const actions = {
startShift({ commit }, agentId) {
return ShiftService.startShift(agentId)
.then((response) => {
if (response.status === 200) {
commit('START_SHIFT', response.data.aggregateId)
}
})
.catch((error) => {
console.log(error)
if (error.response.status === 401) {
console.log('Error in Response')
}
})
},
async updateEventsSubscription({ dispatch, commit, rootState }, agentId) {
await dispatch('startShift', agentId)
const shiftId = state.shiftId
await dispatch('websocket/processWebsocket', null, { root: true })
let agentShiftInfo = {
aggregateId: state.shiftId,
connectionId: rootState.websocket.connectionId,
}
console.log(agentShiftInfo)
return ShiftService.updateEventsSubscription(shiftId, agentShiftInfo)
.then((response) => {
commit('UPDATE_EVENTS_SUBSCRIPTION', response.data)
})
.catch((error) => {
if (error.response.status === 401) {
console.log('Error in Response')
}
})
},
}
export const mutations = {
START_SHIFT(state, shiftId) {
state.shiftId = shiftId
console.log(`Retrieving Shift ID: ${state.shiftId}`)
},
UPDATE_EVENTS_SUBSCRIPTION(state, agentShiftInfo) {
state.agentShiftInfo = agentShiftInfo
},
}
You should convert your WebSocket action into a promise that resolves when WebSocket is connected.:
export const actions = {
processWebsocket({ commit }) {
return new Promise(resolve=> {
const v = this
this.ws = new WebSocket('mywebsocket')
this.ws.onopen = function (event) {
commit('SET_CONNECTION', event.type)
v.ws.send('message')
resolve();
}
this.ws.onmessage = function (event) {
commit('SET_REMOTE_DATA', event)
}
this.ws.onerror = function (event) {
console.log('webSocket: on error: ', event)
}
this.ws.onclose = function (event) {
console.log('webSocket: on close: ', event)
commit('SET_CONNECTION')
ws = null
setTimeout(startWebsocket, 5000)
}
});
},
}
So I realized that I have to resolve the promise on the this.ws.message instead. By doing that all my data is populated accordingly, there's still sync issues (I can't feed the websocket state at the moment because due to its async behaviour the state is not there yet when other components try to use it via: rootGetters.websocket.incomingChats for example) but I guess that's part of another question. Here's the final version of the module action:
export const actions = {
processWebsocket({ commit }) {
return new Promise((resolve) => {
const v = this
this.ws = new WebSocket('wss://ws.rubiko.io')
this.ws.onopen = function (event) {
commit('SET_CONNECTION', event.type)
v.ws.send('message')
}
this.ws.onmessage = function (event) {
commit('SET_REMOTE_DATA', event)
resolve(event)
}
this.ws.onerror = function (event) {
console.log('webSocket: on error: ', event)
}
this.ws.onclose = function (event) {
console.log('webSocket: on close: ', event)
commit('SET_CONNECTION')
ws = null
setTimeout(startWebsocket, 5000)
}
})
},
}
Anyways, thanks #Eldar you were in the right path.

Then Function Running before Store Action in Vue

So in my brands.js store I have this action which calls the API:
getBrandMerchants({ commit }, id) {
commit('setLoading', true);
BrandService.getBrandMerchants(id)
.then((response) => {
commit('setBrand', formatter.deserialize(response.data.result.brand));
commit('setMerchants', formatter.deserialize(response.data.result.merchants));
commit('setLoading', false);
console.log('First');
})
.catch((error) => {
if (error.response.status === 401) {
dispatch('alert/error', error.response, { root: true });
} else {
Toast.open({
type: 'is-danger', message: error.response.data.meta.message,
});
}
});
},
In my components I have the following snippets:
...mapState('brands', ['merchants']),
...mapActions('brands', ['getBrandMerchants']),
When I try to run this method in my component:
addMerchantsToBrandGroup(index) {
const { id } = this.rows[index].brand;
if (id === null) { return; }
this.getBrandMerchants(id)
.then(() => {
console.log('Second');
this.rows[index].merchants = this.merchants
});
},
console results to
Second
First
How can I make it so console returns
First then Second?
First
Second
As mentioned by #deceze:
Adding async and await to:
async getBrandMerchants({ commit }, id) {
commit('setLoading', true);
await BrandService.getBrandMerchants(id)
.then((response) => {
commit('setBrand', formatter.deserialize(response.data.result.brand));
commit('setMerchants', formatter.deserialize(response.data.result.merchants));
commit('setLoading', false);
console.log('First');
})
.catch((error) => {
if (error.response.status === 401) {
dispatch('alert/error', error.response, { root: true });
} else {
Toast.open({
type: 'is-danger', message: error.response.data.meta.message,
});
}
});
},
and
async addMerchantsToBrandGroup(index) {
const { id } = this.rows[index].brand;
if (id === null) { return; }
await this.getBrandMerchants(id)
console.log('Second');
this.rows[index].merchants = this.merchants
},
Solved the problem. Thanks!

Add both settimeout and timeout to in the array loop

I am looping the array using bluebird map method and then using each row as a payload to my apicall function. Everything works perfectly but I want to incorporate timeout method when response from the api takes more than 10 seconds and also settimeout method to delay 2 seconds after each api call. Please let me know how can I acheive this. I am fine without using bluebird. Thanks in advance.
handleSubmit = () => {
Promise.map(this.props.data, row => {
return apiCall(api, row).then((response) => {
if(response){
console.log(response)
} else{
console.log("failed")
}
})
}, { concurrency: 1 } )
}
apiCall: (api, input ) => {
switch (process.env.NODE_ENV) {
case 'production': { // Production environment
return new Promise((resolve) => {
window.runApi(api, input, (response) => {
if (typeof response === 'string') {
const jsonResponse = JSON.parse(response);
resolve(jsonResponse);
} else {
resolve(response);
}
});
});
}
default: {
const requestBody = input;
if (input !== "") {
requestBody.username = "user";
requestBody.password = "password";
}
const requestUrl = `api`;
return fetch(requestUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody),
})
.then(res => res.json());
}
}
}

Facebook graph API: return object from GraphRequest callback

I have a function that successfully makes requests, but am having trouble translating it to the React-Redux data flow because I can't figure out how to return the object that is received in the callback.
What I currently have doesn't work, but I am confident it makes the request successfully because I can see it when I console.log it.
import FBSDK, { AccessToken, GraphRequest, GraphRequestManager } from 'react-native-fbsdk'
export const callback = (error, result) => {
if (error) {
console.log(error);
return error
} else {
console.log(result);
return result;
}
}
export const graphRequestFor = fields => {
AccessToken.getCurrentAccessToken()
.then(token => {
console.log(token);
const request = new GraphRequest(
'/me',
{
accessToken: token.accessToken,
parameters: {
fields: {
string: fields
}
}
}, callback
)
new GraphRequestManager().addRequest(request).start()
})
}
export const login = () => {
graphRequestFor('first_name, last_name')
.then(results => {
return results
}) //undefined
}
Not an answer to my direct question, but a solution to my problem is to make the api call directly inside the action and dispatching the object from the callback
import FBSDK, { AccessToken, GraphRequest, GraphRequestManager } from 'react-native-fbsdk'
export const login = params => dispatch => {
AccessToken.getCurrentAccessToken()
.then(token => {
const request = new GraphRequest(
'/me',
{
accessToken: token.accessToken,
parameters: {
fields: {
string: params
}
}
}, (error, result) => {
if (error) {
console.log(error);
return dispatch(receiveCurrentUser(error))
} else {
return dispatch(receiveCurrentUser(result))
}
}
)
new GraphRequestManager().addRequest(request).start()
})
}

Categories