How To Use Emit in Vue.Js? - vue.js

In this code, I use Random Axios Data in getMembers function.
I wonder if I use the same Data in getMember. As far as I know in this case I can use this.$emit
but I have no idea how to use this.
I want to get exact data in getMember(idx)
methods: {
getMembers() {
var vm = this;
this.axios.get('https://randomuser.me/api/?results=5')
.then(res => {
vm.members = res.data.results;
console.log(vm.members);
})
.catch(error => {
console.log(error);
})
},
getMember(idx) {
this.modal = true;
var vm = this;
console.log(idx);
this.axios.get('https://randomuser.me/api/')
.then(res => {
vm.member = res.data.results;
console.log(vm.member);
})
.catch(error => {
console.log(error);
})
},
},
};

Related

use a function in action of auth modules in wizard module in vuex in vue

I have this function in auth.module.js:
async [VERIFY_AUTH](context) {
if (JwtService.getToken()) {
ApiService.setTokenAxios();
return (
ApiService.get("api/customer/me")
.then(({ data }) => {
console.log("auth request - useer:", data);
context.commit(SET_AUTH, data);
})
///////////
.catch(({ response }) => {
console.log(response);
context.commit(SET_ERROR, serviceErrors(response.data));
})
);
} else {
context.commit(PURGE_AUTH);
}
},
I want dispatch it in wizard.modules.js
[SPOUSES](context, data) {
console.log(data);
return new Promise(() => {
ApiService.post(`api/customer/${data.id}/spouses`, data.form).then(
({ data }) => {
console.log(data);
context.dispatch("auth/VERIFY_AUTH", null, { root: true });
}
);
});
},
I try it but it dont work
do you know what should I do?

Getting JSON info from API

I'm using Axios(Apisauce) to connect API to React Native App;
this is the JSON file I'm trying to show in-app using FlatList :
{
"data": {
"sideMenu": {
"url": "https://google.com",
"icons": [
{
"id": 1,
"url": "https://google.com",
"status": 1
},
]
},
}
}
when I try to log it into the console, using console.log(response.data) returns all API info, but using console.log(response.data.data) doesn't return the object I'm looking for!
I've tried JSON.stringify() or toString() but none of them seem to Work.
my Axios Code :
const getServices = () => {
const service = "https://api.team-grp.ir/app/json/services2.json/";
return client.get(service);
};
My Source Code:
const ServiceInfo = async () => {
await getServices()
.then((response) => {
if (response.ok) {
setServicesData(response.data.data);
}
})
.catch((error) => {
console.warn(error);
setServicesData([]);
});
};
useEffect(() => {
ServiceInfo();
});
you should not use async/await with .then/.cache ...
this code is working for me:
(you can also see my sample code image at the bottom of this answer with a fake getService function, and you will see that logged response is correct)
const ServiceInfo = () => {
getServices().then((response) => {
if (response.ok) {
setServicesData(response.data.data);
}
})
.catch((error) => {
console.warn(error);
setServicesData([]);
});
};
useEffect(() => {
ServiceInfo();
}, []);
const ServiceInfo = async () => {
await getServices()
.then((response) => {
return response.json();
})
.then((response) => {
setServicesData(response.data);
})
.catch((error) => {
console.warn(error);
setServicesData([]);
});
};
Try this

Getting variable from AsyncStorage and putting into Axios

I have been trying to get a variable from AsyncStorage and then put it into an Axios get request. The problem is that the variable is not updating to the data that is retrieved from AsyncStorage. How do I make it do that?
Here is my code:
const [sku, setSku] = useState('')
const STORAGE_KEY_SKU = '#save_sku'
const readSku = async () => {
try {
const selectedSku = await AsyncStorage.getItem(STORAGE_KEY_SKU)
if (selectedSku !== null) {
setSku(selectedSku)
}
} catch (e) {
alert('Failed to fetch the data from storage')
}
}
useEffect(() => {
readSku()
}, []);
useEffect(() => {
Axios.get(`https://api.vexdb.io/v1/get_matches?sku=${sku}`)
.then(({ data }) => {
//console.log("defaultApp -> data", data)
setData(data.result)
})
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, []);
Im trying to put get the sku variable from the state from AsyncStorage, but the ${sku} in the axios get request link is not working, the sku is blank in that statement.
Please help, thanks!
useFocusEffect(() => {
readSku()
}, []);
const STORAGE_KEY_SKU = '#save_sku'
// to get the session username from localstorage
const readSku = async () => {
try {
const selectedSku = await AsyncStorage.getItem(STORAGE_KEY_SKU)
if (selectedSku !== null) {
setSku(selectedSku)
}
} catch (e) {
console.log(e);
}
}
const setSku = async (selectedSku) => {
Axios.get(`https://api.vexdb.io/v1/get_matches?sku=${selectedSku}`)
.then(({ data }) => {
//console.log("defaultApp -> data", data)
setData(data.result)
})
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}

Cannot assign axios response value to a variable - vue.js

I created an array lists that contains a few strings.
Now I want to loop through lists (i.e., in getSubs()) and make an Axios request. This request should contain one string from lists each time.
My code:
computed: {
subscribers: {
get() {
return this.$store.state.subscribers;
},
set(value) {
this.$store.commit('updateSubscribers', value);
},
},
},
methods: {
getLodzkie() {
axios
.get(`correct_domain/lodzkietargi/get`)
.then((response) => {
this.subscribers = [];
this.subscribers.push.apply(this.subscribers, response.data)
})
.catch(function(error) {
console.log(error);
})
},
getSubs() {
function getSub(value) {
axios
.get(`correct_domain/${value}/get`)
.then((response) => {
this.subscribers.push.apply(this.subscribers, response.data)
})
.catch(function(error) {
console.log(error);
});
console.log(value);
}
this.lists.forEach(function(entry) {
getSub.call(null, entry);
});
},
getLodzkie() works beautifully
Thank You a lot #ourmandave. That helped me perfectly.
Rewrote function below:
getSubs() {
let listsReqs = this.lists.map(list => {
return axios.get(`correct_domain/${list}/get`);
});
axios.all(listsReqs)
.then(axios.spread((...responses) => {
responses.forEach(res => this.subscribers.push.apply(this.subscribers, res.data));
})
)},

How do I write a perfect vue.js action to fetch data from server with proper error handling?

export const fetchEnvironmentsData = ({ commit }, params) => {
Vue.http.get('/environments', { params })
.then(response => response.json())
.then(data => {
if (data) {
commit('mutateUpdateEnvironmentData', data);
}
}).catch(function(error) {
alert('Could not load data, Please try again later');
});
};
How do I handle internal server error and empty response from server?
const error = () => alert('Could not load data, Please try again later');
Vue.http.get('/environments', { params })
.then(response => {
const data = response.json();
if (data) {
commit('mutateUpdateEnvironmentData', data);
} else {
error();
}
}, error);
or
Vue.http.get('/environments', { params })
.then(response => response.json(), () => null)
.then(data => {
if (data) {
commit('mutateUpdateEnvironmentData', data);
} else {
alert('Could not load data, Please try again later');
}
});