I have the code below:
const someResult = arr.map(value => ({
props1: value.props1,
props2: value.props2
})
is there any way to make the code formatting look like this in vscode?
const someResult = arr
.map(value => ({
props1: value.props1,
props2: value.props2
})
Related
There is a request to Firebase, using then I add new elements to the array. If you output console.log, then there are elements, but lenght = 0 and loops do not work.
export const useLastMessageDialogs = (messagesStatus: StatusDialogType): UserMessageType[] => {
const messages: string[] = [];
useEffect(() => {
const querySideDialogs = query(
collection(firestoreDb, 'questions'),
where('status', '==', messagesStatus)
);
onSnapshot(querySideDialogs, (dialogs) => {
dialogs.docChanges().forEach((dialog) => {
getDocs(
query(
collection(firestoreDb, 'questions', dialog.doc.id, 'messages'),
orderBy('timestamp', 'desc'),
limit(1)
)
).then((response) => {
response.forEach((message) => {
messages.push('bebebe');
});
});
});
});
}, [messagesStatus]);
console.log(messages); // [0: "bebebe", 1: "bebebe" length: 2]
console.log(messages.length); // 0
return [];
};
I took it to a separate service and connected it via redux-saga
I'm trying to filter a players array by comparing the names property to a roster array and rendering the matches from the players array.
When a user selects a year the getCollegeRoster() function returns players who have a year property matching the selection. From there I'm trying to filter and display the .name matches from the players array, but it seems i'm unable to update playerStateValue. I'm using recoil to manage state. Any insight would be much appreciated.
const getCollegeRoster = async () => {
setLoading(true);
try {
const playersQuery = query(
collection(firestore, `colleges/${communityData.id}/rosters`),
where("year", "==", selection),
);
const playerDocs = await getDocs(playersQuery);
const collegeRoster = playerDocs.docs.map((doc) => ({ id: doc.id, ...doc.data() }));
setRoster(collegeRoster as unknown as Roster[]);
console.log('collegePlayers', roster);
} catch (error: any) {
console.log("getCollegePlayers error", error.message);
}
setLoading(false);
};
const onSelection = (newSelection: any) => {
setSelection(newSelection);
console.log('newselect', newSelection)
getCollegeRoster();
const filteredArray = [...playerStateValue.players].filter((el) => ({
name: el.name,
match: [...roster].some((f) => f.name === el.name)
})
);
setPlayerStateValue((prev) => ({
...prev,
players: filteredArray as Player[],
playersCache: {
...prev.playersCache,
[communityData?.id!]: filteredArray as Player[],
},
playerUpdateRequired: false,
}));
} ```
also tried adding setplayerstatevalue into the getcollegeroster function:
onst getCollegeRoster = async () => {
console.log("WE ARE GETTING Players!!!");
console.log('communitydata', communityData);
setLoading(true);
try {
const playersQuery = query(
collection(firestore, `colleges/${communityData.id}/rosters`),
where("year", "==", selection),
);
const playerDocs = await getDocs(playersQuery);
const collegeRoster = playerDocs.docs.map((doc) => ({ id: doc.id, ...doc.data() }));
setRoster(collegeRoster as unknown as Roster[]);
console.log('collegePlayers', roster);
const filteredArray = [...playerStateValue.players].filter((el) => ({
name: el.name,
match: [...roster].some((f) => f.name === el.name)
})
);
setPlayerStateValue((prev) => ({
...prev,
players: filteredArray as Player[],
playersCache: {
...prev.playersCache,
[communityData?.id!]: filteredArray as Player[],
},
playerUpdateRequired: false,
}));
} catch (error: any) {
console.log("getCollegePlayers error", error.message);
}
setLoading(false);
};
{playerStateValue.players.map((player: Player, index) => (
<PlayerItem
key={player.id}
player={player}
// postIdx={index}
onPlayerVote={onPlayerVote}
userVoteValue={
playerStateValue.playerVotes.find((item) => item.playerId === player.id)
?.voteValue
}
onSelectPlayer={onSelectPlayer}
/>
I believe I found the problem. getCollegeRoster() is an async function which means it is being executed asynchronous.
That function is responsible for updating roster and you are using roster inside your filtering while it is being asynchronously updated.
There is no guarantee that roster is updated by the time you filter your array.
You have two ways of solving this. Either you execute setPlayerStateValue() inside of getCollegeRoster() or you wait for getCollegeRoster() to be done by preappending it with await and your onSelection function with async:
const onSelection = async (newSelection: any) => {
setSelection(newSelection);
console.log("newselect", newSelection);
await getCollegeRoster();
const filteredArray = [...playerStateValue.players].filter((el) => ({
name: el.name,
match: [...roster].some((f) => f.name === el.name),
}));
...
Edit:
Another scenario I can think of is that playerStateValue might be the culprit. In React setState works asynchronous as well, if you access playerStateValue via curr/prev-callback, it is guaranteed that you are accessing the values of the current state object while updating the state. Try this use of setPlayerStateValue:
setPlayerStateValue((prev) => {
const filteredArray = prev.players.filter((el) => ({
name: el.name,
match: [...roster].some((f) => f.name === el.name),
})) as Player[];
return {
...prev,
players: filteredArray,
playersCache: {
...prev.playersCache,
[communityData?.id!]: filteredArray,
},
playerUpdateRequired: false,
};
});
Can someone please assist in following:
I have to assert array with x elements (usually not more than 6 or 7) and if there is any duplicates, it has to throw error - or step to fail. So far I did the following:
Cypress.Commands.add('addTextElementIntoArray', (list) => {
var textsArray = []
cy.xpath(list).each(($el) => {
const text = $el.text().replace(' ', '')
textsArray.push(text)
cy.log(text)
})
})
Tried this solution: Find duplicates, but it does not work in Cypress. How can I solve this?
Thank you in advance
Found solution, and here it is:
Cypress.Commands.add('addTextElementIntoArray', (list) => {
var textsArray = []
var non_unique = []
cy.xpath(list)
.each(($el) => {
const text = $el.text().replace(' ', '')
textsArray.push(text)
cy.log(text)
non_unique = textsArray.filter((item, i) =>
textsArray.includes(item, i + 1)
)
})
.then(() => {
expect(non_unique.length).equal(0)
})
})
Using the answer from the linked question in Cypress,
Cypress.Commands.add('listHasNoDuplicates', (list) => {
cy.xpath(list)
.then($els => [...$els].map(el => el.innerText.trim()))
.then(texts => {
const unique = new Set(texts)
expect(texts.length).to.eq(unique.size)
})
})
})
so I have been working on a web app similar to Instagram and I am trying to paginate the data(posts) from firestore, I tried the below code but on calling the function loadMorePosts it shows only the next two posts without retaining the previous new posts
Question 1: Why doesn't it retain the previous new posts while setting the post in function loadMorePosts?
I tried applying spread operator but it doesn't help so
setPosts(...posts,
snapShot.docs.map((doc) => ({ id: doc.id, post: doc.data() }))
);
Question 2: Why snapShot.docs[snapShot.docs.length - 1] is an object, shouldn't it be a number?
Question 3: How to know that there are no more post to fetch?
Code :
const [posts, setPosts] = useState([]);
const [latestDoc, setLatestDoc] = useState(null);
const test = [];
useEffect(() => {
const unsub = db
.collection("posts")
.orderBy("timestamp", "desc")
.limit(2)
.onSnapshot((snapShot) => {
setPosts(
snapShot.docs.map((doc) => ({ id: doc.id, post: doc.data() }))
);
setLatestDoc(snapShot.docs[snapShot.docs.length - 1]);
});
return unsub;
}, []);
const loadMorePosts = async () => {
db.collection("posts")
.orderBy("timestamp", "desc")
.startAfter(latestDoc)
.limit(2)
.onSnapshot((snapShot) => {
setPosts(
snapShot.docs.map((doc) => ({ id: doc.id, post: doc.data() }))
);
setLatestDoc(snapShot.docs[snapShot.docs.length - 1]);
});
console.log(test);
console.log(latestDoc);
};
Question 1: Why doesn't it retain the previous new posts while setting the post in function loadMorePosts?
Because post is an array, use have to do this:
setPosts([...posts,
...snapShot.docs.map((doc) => ({ id: doc.id, post: doc.data() }))
]);
Question 2: Why snapShot.docs[snapShot.docs.length - 1] is an object, shouldn't it be a number?
It is obviously an object, how can it be a number? It like:
snapShot.docs = [ {object 1}, {object 2}, {object 3} ]
snapShot.docs[snapShot.docs.length - 1] = snapShot.docs[2] = {object 3}
Question 3: How to know that there are no more post to fetch?
You could do something like this:
const [ hasMore, setHasMore ] = useState(false);
setHasMore(snapShot.docs.length > 0);
I have an app that read data from external devices. These data are like acceleration, gyroscopic, magnetometer and pressure.
I'm trying to read the data in this way:
async setupNotifications2(device) {
let i = 0
const service = this.serviceGeneral();
while(i<10 ) {
i++
const promises = [
device.readCharacteristicForService(service, this.AccGyrMg),
device.readCharacteristicForService(service, this.Pressure)
]
Promise.all(promises)
.then((values) => {
// const time = new Date().getMilliseconds()
const time = bufAccGyrMg.readInt16LE(0);
const [...acc_sx] = [0,2, 4, 6].map(index => bufAccGyrMg.readInt16LE(index));
this.setState(state => ({acc_sx,array_acc_sx: [...state.array_acc_sx,[time , acc_sx]]}));
const [...gyr_sx] = [8, 10, 12].map(index => bufAccGyrMg.readInt16LE(index));
this.setState(state => ({gyr_sx,array_gyr_sx: [...state.array_gyr_sx,[time , gyr_sx]]}));
const [...mg_sx] = [14,16,18].map(index => bufAccGyrMg.readInt16LE(index));
this.setState(state => ({gyr_sx,array_mg_sx: [...state.array_mg_sx,[time , mg_sx]]}));
const bufPressure = Buffer.from(values[1].value, "base64");
const [...pressure_sx] = [0, 2, 4, 6, 8].map(index => bufPressure.readUInt16LE(index));
this.setState(state => ({pressure_sx,array_pressure_sx: [...state.array_pressure_sx,[time, pressure_sx]]}));
})
}
}
Now I have insert a condition inside a while only to try the code.
When I start the app, I receive this error:
YellowBox.js:67 Possible Unhandled Promise Rejection (id: 0):
BleError: Operation was rejected
How can I do, in your opinion?? Thank you.
I refactored your code a bit to help get rid of the Unhandled Promise Rejection error and help you point down the issue:
async setupNotifications2(device) {
//first of all, put everything inside a big try/catch block
try {
let i = 0
const service = this.serviceGeneral();
while(i<10 ) {
i++
const promises = [
// then make sure every promise passed to Promise.all() catches its own errors
device.readCharacteristicForService(service, this.AccGyrMg).catch( e => console.log(`err in first readCharacteristicForService `, e)),
device.readCharacteristicForService(service, this.Pressure).catch( e => console.log(`err in second readCharacteristicForService `, e))
]
// giben you're in an async function, you can do this to simplify a bit your code:
const values = await Promise.all(promises);
// const time = new Date().getMilliseconds()
const time = bufAccGyrMg.readInt16LE(0);
// this is an array, no need to overcomplicate with destructuring assignment... you can do the same below
const acc_sx = [0,2, 4, 6].map(index => bufAccGyrMg.readInt16LE(index));
this.setState(state => ({acc_sx,array_acc_sx: [...state.array_acc_sx,[time , acc_sx]]}));
const [...gyr_sx] = [8, 10, 12].map(index => bufAccGyrMg.readInt16LE(index));
this.setState(state => ({gyr_sx,array_gyr_sx: [...state.array_gyr_sx,[time , gyr_sx]]}));
const [...mg_sx] = [14,16,18].map(index => bufAccGyrMg.readInt16LE(index));
this.setState(state => ({gyr_sx,array_mg_sx: [...state.array_mg_sx,[time , mg_sx]]}));
const bufPressure = Buffer.from(values[1].value, "base64");
const [...pressure_sx] = [0, 2, 4, 6, 8].map(index => bufPressure.readUInt16LE(index));
this.setState(state => ({pressure_sx,array_pressure_sx: [...state.array_pressure_sx,[time, pressure_sx]]}));
} catch (err){
console.error(`general error: `, err)
}
}