Mutation for notifications in Vue.js - vue.js

I have a store for notifications in my application. I can load all notifications and mark one notification as read. I wrote actions and mutations for each case. The last action is for marking all notifications as read but I am struggling with writing a mutation for this (commented part).
const actions = {
notifications(context) {
document.client
.get_notifications()
.then(ca => {
S_Helper.cmt_data(ca, "load_notifications", this);
})
.catch(error => {
ClientAlert.std_fail_with_err(error);
});
},
readNotification(id, params) {
document.client
.read_notification({ id, params })
.then(ca => {
if (ca.is_success()) {
context.commit("mark_notification", id);
} else {
ClientAlert.std_fail();
}
})
.catch(error => {
ClientAlert.std_fail_with_err(error);
});
},
readAllNotifications(context, params) {
params = params || {};
document.client
.read_all_notifications(params)
.then(ca => {
if (ca.is_success()) {
context.commit("mark_all_notifications", this);
} else {
ClientAlert.std_fail();
}
})
.catch(error => {
ClientAlert.std_fail_with_err(error);
});
}
};
const mutations = {
load_notifications(context, data) {
context.notifications = data;
},
mark_notification(state, id) {
let new_data = state.notifications.map(function(element) {
if (!!element.id && element.id === id) {
element.viewed = true;
}
return element;
});
state.notifications = new_data;
}
//mark_all_notifications(context, data) {
//}
};

mark_all_notifications(state, data) {
state.notifications = state.notifications.map(notification => {
notification.viewed = true
return notification
})
}
A simple map should work.

Related

Create VIdeocall room with multiple users using WebRtc and firebase

i am trying to create a room video call something like Whatsapp with firebase as signalisation server for two users it works perfect as expected but when a third user join everything stop working
if the user A the first who join and the user B the second until the user C join everything work fine but when C join user A freeze and lost user B connection and B share screen with C but also sometimes freezing
here is my code
onst joinRoom = async () => {
const roomRef = await firestore().collection('meets').doc(params.callId);
roomRef
.collection('users')
.add({name, type: 'join'})
.then(() => {
roomRef
.collection('users')
.get()
.then(async querySnapshot => {
if (querySnapshot.empty) {
console.log('EMPTY');
} else {
querySnapshot.forEach(async snap => {
if (snap.data().name !== name && snap.data().type === 'join') {
// data.push(snap.data().name);
await creatOffer(snap.data().name);
}
// if (data.length > 0) {
// Promise.all(data).then(async user => {
// return await creatOffer(user);
// });
// }
});
}
});
});
// // listen on any new offers
roomRef.collection('offers').onSnapshot(data => {
data.docChanges().forEach(async change => {
if (change.type === 'added') {
// console.log('changes', change.doc.data());
if (change.doc.data().to === name) {
await createAnswer(change.doc.data().from, change.doc.data().offer);
}
}
});
});
//listen to answers
roomRef.collection('answers').onSnapshot(async snapshot => {
snapshot.docChanges().forEach(async change => {
if (change.type === 'added') {
const pc = pcPeers[change.doc.data().from];
if (change.doc.data().to === name) {
const rtcSessionDescription = new RTCSessionDescription(
change.doc.data().answer,
);
if (pc && rtcSessionDescription) {
await pc.setRemoteDescription(rtcSessionDescription);
}
}
}
});
});
//listen to candidate change
roomRef.collection('candidates').onSnapshot(async snapshot => {
snapshot.docChanges().forEach(async change => {
// console.log('answers', change.doc.data());
if (change.type === 'added') {
console.log('added', Platform.OS);
if (change.doc.data().to === name) {
const pc = pcPeers[change.doc.data().from];
// console.log(pc);
if (pc) {
await pc.addIceCandidate(
new RTCIceCandidate(change.doc.data().candidate),
);
}
}
}
});
});
};
and function to create offer
const creatOffer = async to => {
try {
const {roomRef, localPC} = await initializePeer(to);
const offer = await localPC.createOffer();
// console.log('offer', offer);
if (offer) {
await localPC.setLocalDescription(offer);
await roomRef.collection('offers').add({from: name, to, offer});
}
pcPeers = {...pcPeers, [to]: localPC};
} catch (e) {
console.log(e);
}
};
function to create answer
const createAnswer = async (from, offer) => {
try {
const {localPC, roomRef} = await initializePeer(from);
await localPC.setRemoteDescription(new RTCSessionDescription(offer));
const answer = await localPC.createAnswer();
await localPC.setLocalDescription(answer);
// await checkIfAnswerAlreadyCreated(from, name);
await roomRef.collection('answers').add({from: name, to: from, answer});
pcPeers = {...pcPeers, [from]: localPC};
} catch (e) {
console.log(e);
}
};
and here is how i initialise a peer
setLocalStream(initialStream);
const roomRef = await firestore().collection('meets').doc(params.callId);
const collection = roomRef.collection('candidates');
localPC.onicecandidate = async e => {
if (!e.candidate) {
return;
}
// console.log('canditates', Platform.OS);
const state = localPC.iceGatheringState;
if (state !== 'complete') {
await collection.add({
from: name,
candidate: e.candidate.toJSON(),
to,
date: new Date(),
});
} else {
Alert.alert('tes');
}
// InCallManager.setForceSpeakerphoneOn(true);
// InCallManager.setSpeakerphoneOn(true);
};
localPC.onsignalingstatechange = async event => {
// when the signal state become stable record the data and stop ringback
if (event.target.signalingState === 'stable') {
if (Platform.OS === 'ios') {
localStream?.getVideoTracks().forEach(track => {
//For ios to trigger the camera on
track._switchCamera();
track._switchCamera();
});
}
}
};
localPC.onaddstream = e => {
if (e?.stream) {
// console.log(
// `RemotePC received the stream call ${Platform.OS}_${Platform.Version}`,
// e?.stream,
// );
console.log(Platform.OS, ' ', Platform.Version);
if (remoteStream === null) {
// Alert.alert('stream 1');
setRemoteStream(e?.stream);
} else {
// Alert.alert('stream 2');
setRemoteStream_(e?.stream);
}
}
};
return {localPC, roomRef};
};
can anyone help me with some hints where is tthe problem i’ve created for my self here and thank you

Using AsyncStorage to show screen on first login

I'm trying to only show the disclosure screen the first time the user logs in by using AsyncStorage. Currently getData is returning a Promise and it goes straight to the landing screen on first login.
Could I get some help to get this functioning the way I want it to?
This is my login handler:
const key = 'key';
const storeData = async () => {
try {
await AsyncStorage.setItem('key', 'true');
} catch (error) {
// saving failed
console.log(error.message);
}
};
const getData = async key => {
let value = '';
try {
value = await AsyncStorage.getItem(key);
return JSON.parse(value);
} catch (e) {
console.log(error.message);
}
};
const _loginHandler = () => {
if (userName == '' || password == '') {
console.log('gagagagagagagagagagagagagagagagag');
} else {
setShowLoading(true);
const payload = {userName: userName.trim(), password: password.trim()};
setUserName('');
setPassword('');
_UserLoginHandler(payload).then(data => {
setShowLoading(false);
if (data.error) {
GlobalShowSnackBar(data.error);
} else {
setTimeout(() => {
setUserId(data);
//props.navigation.replace(getData("key")?'Landing':'Disclosure')
console.log('Key Value ' + JSON.stringify(getData('key'))); <-- this outputs Key Value {"_U":0,"_V":0,"_W":null,"_X":null}
if (getData('key')) {
props.navigation.navigate('Landing');
} else {
storeData(key);
props.navigation.navigate('Disclosure');
}
}, 500);
}
});
}
};
I got it to work with
getData('key').then(val => {
if (val) {
props.navigation.navigate('Landing');
} else {
storeData(key);
props.navigation.navigate('Disclosure');
}
});

Join 3 res.data vue.js

I want to join three res.data (carsIn,PositionUsed,position),this res.data I get it by axios.get
carsIn(id,username,useraddress,userphone,plate)
PositionUsed(id_pos,id_car,enterdate)
position(id_pos,name)
I tried this solution but I need to refresh 3 time to get data in array mergedd
any solution ?
I want to get mergedd (username,useraddress,userphone,plate,enterdate,name)
export default {
name: "Courses",
data() {
return {
carsIn: [],
PositionUsed:[],
merged:[],
positions:[],
mergedd:[],
message: "",
INSTRUCTOR: "in28minutes"
};
},
computed: {
currentUser() {
return this.$store.state.auth.user;
}
},
mounted() {
if (!this.currentUser) {
this.$router.push('/login');
}
},
methods: {
refreshCourses() {
clientService.retrieveAllCarsIn(this.INSTRUCTOR)
.then((res) => {
this.carsIn= res.data;
});
clientService.retrieveAllPositionOcp(this.INSTRUCTOR)
.then((res) => {
this.PositionUsed= res.data;
for(let i=0; i<this.carsIn.length; i++) {
this.merged.push({
...this.carsIn[i],
...(this.PositionUsed.find((itmInner) =>
itmInner.id_car === this.carsIn[i].plate))}
);
}
});
clientService.retrieveAllPositions(this.INSTRUCTOR)
.then((res) => {
this.positions = res.data;
for(let i=0; i<this.merged.length; i++) {
this.mergedd.push({
...this.merged[i],
...(this.positions.find((itmInner) => itmInner.id_pos
=== this.merged[i].id_pos))}
);
}
});
}
},
created() {
this.refreshCourses();
}
}
This is the best solution but it will only work if clientService.retrieveAllCarsIn , clientService.retrieveAllPositionOcp and clientService.retrieveAllPositions are promises
refreshCourses() {
Promise.all([clientService.retrieveAllCarsIn(this.INSTRUCTOR) , clientService.retrieveAllPositionOcp(this.INSTRUCTOR)] , clientService.retrieveAllPositions(this.INSTRUCTOR)).then((response) =>{
this.carsIn= response[0].data;
this.PositionUsed= response[1].data;
this.positions = response[2].data;
}).catch((err) =>{
//error handler
}).finally(() =>{
})
}
Seems like the you can rewrite your function something like this:
refreshCourses() {
// Get data for all 3 requests at the same time
const [courses, pos, positions] = Promise.all([clientService.retrieveAllCarsIn(this.INSTRUCTOR), clientService.retrieveAllPositionOcp(this.INSTRUCTOR), clientService.retrieveAllPositions(this.INSTRUCTOR)]);
// Now iterate over courses
this.mergedd = courses.map(({
id,
namecourse,
desc,
plate
}) => {
// Get date from pos array
const {
date,
id_position
} = pos.find(p => p.id_car === plate); // Or p.id_course === id
// Get nameposition from positions array
const {
nameposition
} = positions.find(p => p.id === id_position);
const out = {
id,
namecourse,
desc,
date,
nameposition
}
});
}

In a Redux's Action, Calling a Function with Callbacks (Using async/await with React-Native-Contacts)

I am developing a mobile app, which uses React-Native, Redux and React-Native-Contacts.
In an action creator, I am trying to call a function (from React-Native-Contacts), which has callbacks (rather than promises). Following is my code.
I want the action "acContactImport" to wait for the helper function "fContactImport" to finish before proceeding to the "dispatch" statement. It does not wait for it. How can I make it wait for it?
// Action Creator:
import Contacts from 'react-native-contacts';
import { PermissionsAndroid } from 'react-native';
export const acContactImport = (userID) => {
return async (dispatch) => {
let contactList = [];
try {
// The following statement should be executed asynchronously.
// However, it is not. How can I make it asynchronous?
contactList = await fContactImport();
dispatch({
type: CONTACT_IMPORT,
payload: { contactList: contactList },
});
}
catch (err) {
console.log("acContactImport - catch: ", err);
}
};
};
// Helper Function 1
export const fContactImport = async () => {
let contactList = [];
if (Platform.OS === "android") {
PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.READ_CONTACTS, {
title: "Contacts",
message: "This app would like to view your contacts."
})
.then(() => {
contactList = _loadContacts();
});
} else {
contactList = _loadContacts();
}
}
// Helper Function 2
export const _loadContacts = () => {
Contacts.getAll((err, data2) => {
if (err) {
return [];
}
else {
let candidates = [];
for (let i = 0; i < data2.length; i++) {
let candidateObject = { name: candidateRecord.givenName + " " + candidateRecord.middleName + " " + candidateRecord.familyName };
candidates.push(candidateObject);
}
return contactList;
}
});
}
Apparently, the problem is NOT in the action creator, but in the helper functions, which do not support the new style of promises (async/wait). So, here is the solution...
// Action Creator:
// No changes are required. Original code is good.
// Helper Function 1
export const fContactImport = async () => {
let contactList = [];
if (Platform.OS === "android") {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.READ_CONTACTS,
{
title: "Contacts",
message: "This app would like to view your contacts."
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
contactList = await _loadContacts();
} else {
console.log('Contacts access denied');
}
} catch (err) {
console.warn(err);
}
} else {
contactList = await _loadContacts();
}
return contactList;
}
// Helper Function 2
export const _loadContacts = () => {
return new Promise((resolve, reject) => {
Contacts.getAll((err, data2) => {
if (err) {
reject([]);
}
else {
let candidates = [];
for (let i = 0; i < data2.length; i++) {
let candidateObject = { name: candidateRecord.givenName + " " + candidateRecord.middleName + " " + candidateRecord.familyName };
candidates.push(candidateObject);
}
resolve(candidates);
}
});
});
}

Update array redux

I try to update a now playing state in Redux but everytime i call the update and it passes the check it get's added twice to the state.
result is that my filter when mapping (hide the first item) is not working due to the 2 additions.
Sample reducer:
import {
UPDATE_NOW_PLAYING,
UPDATE_ARTIST_AND_TITLE,
UPDATE_CURRENT_ARTIST
} from '../actions/actionTypes'
import { nowPlayingUrl, showNumberOfTracks, lastFmApiKey } from '../constants'
const currentState = {
playHistory: [],
currentArtist: '',
currentTitle: '',
currentShowName: '',
currentAlbumUrl: 'https://https://url.to.logo/app/app/logo-app.png'
}
const NowPlayingReducer = (state = currentState, action) => {
switch (action.type) {
case UPDATE_ARTIST_AND_TITLE: {
if (state.currentArtist !== action.array[0].artist) {
return {
...state,
playHistory: state.playHistory.concat(action.array[0]),
currentArtist: action.array[0].artist,
currentTitle: action.array[0].title,
currentShowName: action.array[0].showName,
currentAlbumUrl: action.array[0].albumUrl
}
}
return state
}
case UPDATE_NOW_PLAYING: {
return {
...state,
playHistory: action.payload,
currentArtist: action.payload[0].artist,
currentTitle: action.payload[0].title,
currentShowName: action.payload[0].showName,
currentAlbumUrl: action.payload[0].albumUrl
}
}
default: return state
}
}
export default NowPlayingReducer
So it works, but the only part is the second addition somehow :(
//Edit:
componentWillMount() {
this.getNowPlaying()
}
componentDidMount() {
setInterval(async () => {
await this.updateCurrentInformation()
}, 10000);
}
updateCurrentInformation = async () => {
try {
let currentPlayingResponse = await fetch(nowPlayingUrl + 1 )
let currentPlayingJson = await currentPlayingResponse.json()
let newArray = []
Promise.all(
currentPlayingJson.nowplaying.map(async (album) => {
const albumObj = await this.getAlbumInformation(album);
newArray.push(albumObj);
this.props.updateArtistAndTitle(newArray)
})
);
} catch(error) { console.log(error)};
}
togglePlayerType() {
}
getNowPlaying = async () => {
try {
let nowPlayingResponse = await fetch(nowPlayingUrl + showNumberOfTracks);
let nowPlayingJson = await nowPlayingResponse.json();
let newArray = [];
Promise.all(
nowPlayingJson.nowplaying.map(async (album) => {
const albumObj = await this.getAlbumInformation(album);
newArray.push(albumObj);
this.props.updateNowPlaying(newArray);
})
);
} catch (err) {
console.log(err);
}
}
getAlbumInformation = async (album) => {
return new Promise(async (resolve, reject) => {
let id = JSON.stringify(album.id).replace(/"/g, '');
let title = JSON.stringify(album.title)
.replace(/"/g, '')
.replace(/([&][^&; ]+[;])/g, '');
let artist = JSON.stringify(album.artist)
.replace(/"/g, '')
.replace(/([&][^&; ]+[;])/g, '');
let dateTime = JSON.stringify(album.datetime).replace(/"/g, '');
let showName = JSON.stringify(album.showName).replace(/"/g, '');
let albumUrl = 'https://url.to.logo/app/logo-app.png';
let obj = { id, title, artist, dateTime, showName, albumUrl };
try {
let albumResponse = await fetch(
`https://ws.audioscrobbler.com/2.0/?method=track.getInfo&format=json&api_key=${lastFmApiKey}&artist=${artist}&track=${title}`
);
let albumJson = await albumResponse.json();
if (albumJson) {
url = albumJson.track.album.image[3]['#text'];
if (url > '') {
obj.albumUrl = albumJson.track.album.image[3]['#text'];
} else {
obj.albumUrl = 'https://url.to.logo/app/logo-app.png';
}
}
resolve(obj);
} catch (err) {
resolve(obj);
}
});
}