How to access variable inside a function in JavaScript? - javascript

I'm almost finishing my first project with React Native which is an expenditure app.
I'm building a chart from all my expenses in 2 currencies, the code is working I just have a small problem with accessing a local variable.
I would like to access the 2 sum variable inside this function, so I can use it in my return for React Native to build a chart.
// Get $ currency From fire base
const q = query(collection(db, "users"),where("selected", "==", "Gasto"), where("moneda", "==", "$"));
const unsubscribe = onSnapshot(q,(querySnapshot) => {
const dolarCurrency = [];
const months =[];
querySnapshot.forEach((doc) =>{
dolarCurrency.push(doc.data().cantidad);
months.push(doc.data().fecha)
})
const hash = months.map((Day) => ({ Day }));
const hashDolar = dolarCurrency.map(( Amount ) => ({ Amount }))
const output = hash.map(({Day},i) => ({Day, ...hashDolar[i]}));
/// I need this variable below
const sum = output.reduce((acc, cur)=> {
const found = acc.find(val => val.Day === cur.Day)
if(found){
found.Amount+=Number(cur.Amount)
}
else{
acc.push({...cur, Amount: Number(cur.Amount)})
}
return acc
}, [])
})
// Get C$ currency from Firebase
const q2 = query(collection(db, "users"), where("selected", "==", "Gasto"),where("moneda", "==", "C$"));
const unsubscribe2 = onSnapshot(q2, (querySnapshot) =>{
const localCurrency = [];
const months2 = [];
querySnapshot.forEach((doc) => {
localCurrency.push(doc.data().cantidad)
months2.push(doc.data().fecha)
})
const hash = months2.map((Day) => ({ Day }));
const hashLocalCurrency = localCurrency.map(( Amount ) => ({ Amount }))
const output = hash.map(({Day},i) => ({Day, ...hashLocalCurrency[i]}));
/// I need this variable below
const sum = output.reduce((acc, cur)=> {
const found = acc.find(val => val.Day === cur.Day)
if(found){
found.Amount+=Number(cur.Amount)
}
else{
acc.push({...cur, Amount: Number(cur.Amount)})
}
return acc
}, [])
})
Any help or advice is welcome and appreciated!

You can either try state or ref, depends on whether UI part is to be updated, if UI is to be updated then state else ref does the job
const [sum,setSum] = useState(0)
or
const sumRef = useRef(0)
Then after that
const sum = output.reduce((acc, cur)=> {
const found = acc.find(val => val.Day === cur.Day)
if(found){
found.Amount+=Number(cur.Amount)
}
else{
acc.push({...cur, Amount: Number(cur.Amount)})
}
return acc
}, [])
})
You can either setSum(sum) or sumRef.current = sum
Hope it helps , feel free for doubts

Related

Enabling multiple filters for a single array

in my application, there are two types of filters, category and country. However, I am not able to get them to be applied at the same time. For example, I only want the intersection of Category: SaaS + Country: Singapore.
Any advice?
const loadData = props.load
const [card, setCard] = useState(loadData)
const [searchPhrase, setSearchPhrase] = useState("")
const search = (event)=>{
const matchedUsers = loadData.filter((card)=>{
return card.title.toLowerCase().includes(event.target.value.toLowerCase())
})
setCard(matchedUsers)
setSearchPhrase(event.target.value)
}
const filterCountry = (event)=>{
const filteredCards = loadData.filter((card)=>{
return card.country.includes(event.target.value)
})
setCard(filteredCards)
}
const filterCat = (event)=>{
const filteredCards = loadData.filter((card)=>{
return card.cat.includes(event.target.value)
})
setCard(filteredCards)
}
You can change your filter condition to check if the value is in all your considered types
const result = yourData.filter(item => item.country.includes(YOURPHRASE) || item.cat.includes(YOURPHRASE))
you can pass the filtered array as a parameter to the filtering functions :
const search = (event)=>{
const matchedUsers = loadData.filter((card)=>{
return card.title.toLowerCase().includes(event.target.value.toLowerCase())
})
setSearchPhrase(event.target.value);
return matchedUsers
}
const filterCountry = (event,array)=>{
return array.filter((card) => card.country.includes(event.target.value);
}
const filterCat = (event,array)=>{
return array.filter((card) => card.cat.includes(event.target.value);
}
useEffect(() => {
let result = matchedUsers();
result = filterCountry(result);
result = filterCat(result);
setArrayToFilter(result);
}, [searchPhrase]);

Trouble understanding Cloud Function Error

I am new to cloud funcations node.js and type script. I am running the below code and getting the error below and can't make sense of it after watch a ton of videos about promises and searching other questions.
any help would be appreciated.
Function returned undefined, expected Promise or value
exports.compReqUpdated = functions.firestore
.document('/compRequests/{id}')
.onUpdate((change, contex)=>{
const newData = change.after.data();
//const oldData = change.before.data();
const dbConst = admin.firestore();
const reqStatus:string = newData.requestStatus;
const compId:string = newData.compID;
const reqActive:boolean = newData.requestActive;
if (reqStatus == "CANCELED" && reqActive){
const query = dbConst.collection('compRequests').where('compID', '==', compId);
const batch = dbConst.batch();
query.get().then(querySnapshot => {
const docs = querySnapshot.docs;
for (const doc of docs) {
console.log(`Document found at path: ${doc.ref.path}`);
console.log(doc.id);
const docRef = dbConst.collection('compID').doc(doc.id);
batch.update(docRef, {requestStatus: 'CANCELED',requestActive: false});
};
return batch.commit()
})
.catch(result => {console.log(result)});
}else{
return
}
});
The firebase docs state that the callback passed to the onUpdate function should return PromiseLike or any value, but you aren't returning anything right now. If you change your code to something as follows I reckon it should work as expected:
exports.compReqUpdated = functions.firestore
.document('/compRequests/{id}')
.onUpdate((change, contex) => {
const newData = change.after.data();
//const oldData = change.before.data();
const dbConst = admin.firestore();
const reqStatus: string = newData.requestStatus;
const compId: string = newData.compID;
const reqActive: boolean = newData.requestActive;
if (reqStatus == "CANCELED" && reqActive) {
const query = dbConst.collection('compRequests').where('compID', '==', compId);
const batch = dbConst.batch();
return query.get().then(querySnapshot => {
const docs = querySnapshot.docs;
for (const doc of docs) {
console.log(`Document found at path: ${doc.ref.path}`);
console.log(doc.id);
const docRef = dbConst.collection('compID').doc(doc.id);
batch.update(docRef, { requestStatus: 'CANCELED', requestActive: false });
};
return batch.commit()
}).catch(result => { console.log(result) });
} else {
return false;
}
});

How to properly work with promises, Firebase and React's UseEffect hook?

Basically what I'm trying to achieve is to run some code only after a variable is not undefined anymore. However, I'm feeling very confused with the use of promises to await firebase responses, as well as with the use of React's useEffect hook.
I did some research that perhaps listeners are my answer to this? I couldn't really figure out how to implement them, though.
const weekday = moment().isoWeekday()
export const TimeGrid = () => {
const { userObject } = useContext(Context)
//(1) I wish to use the below to generate a list of times
const [LIST_OF_TIMES_FROM_DATABASE, SET_LIST_OF_TIMES_FROM_DATABASE] = useState([])
let businessId
function getBusinessId() {
if (userObject) businessId = userObject.businessId
}
getBusinessId()
//defines function that will run below inside of first useEffect
//also where the list of times is supposed to be set
function getWorkingHoursAccordingToDayOfTheWeek(day, snapshot) {
const workingHours = []
const ALL_AVAILABLE_TIMES = []
workingHours.push(snapshot.data().beginWeek)
workingHours.push(snapshot.data().endWeek)
const [begin, ending] = workingHours
let bgn = moment(begin, 'HH:mm')
const end = moment(ending, 'HH:mm')
let i = 0
while (bgn <= end) {
ALL_AVAILABLE_TIMES.push({
id: i,
type: 'time',
day: 'today',
time: bgn.format('HHmm'),
})
bgn = bgn.add(30, 'minutes')
i++
}
SET_LIST_OF_TIMES_FROM_DATABASE(ALL_AVAILABLE_TIMES) //(2) This is where I set the list, which won't work on its 1st run
}
useEffect(() => {
async function getTimesFromDB() {
const approved = await approvedBusinessService.doc(businessId)
const snapshotApproved = await approved.get()
if (snapshotApproved.exists) {
getWorkingHoursAccordingToDayOfTheWeek(weekday, snapshotApproved)
return
} else {
const pending = await businessPendingApprovalService.doc(businessId)
const snapshotPending = await pending.get()
if (snapshotPending.exists) {
getWorkingHoursAccordingToDayOfTheWeek(weekday, snapshotPending)
}
}
return
}
getTimesFromDB()
}, [userObject])
const allBookedTimes = allBookings.map(element => element.time)
//the below used to be 'listOfTimesJSON.map(item => item.time)' and used to work as it was a static JSON file
//(3) this is sometimes undefined... so all of the code below which relies on this will not run
const listOfTimes = LIST_OF_TIMES_FROM_DATABASE.map(item => item.time)
const [counts, setCounts] = useState({})
useEffect(() => {
const counts = {}
//(4) below will not work as listOfTimes won't exist (because of 'LIST_OF_TIMES_FROM_DATABASE' being undefined)
listOfTimes.forEach(x => {
counts[x] = (counts[x] || 0) + 1
if (allBookedTimes.includes(x)) counts[x] = counts[x] - 1
})
setCounts(counts)
}, [])
const sortedListOfTimesAndCount = Object.keys(counts).sort() //(5) undefined, because 'counts' was undefined.
const displayListOfTimes = sortedListOfTimesAndCount.map(
time =>
time > currentTime && (
<>
<li>
{time}
</li>
</>
),
)
return (
<div>
<ul>{displayListOfTimes}</ul>
</div>
)
}
as per the comments in your code your steps 3 ,4 ,5 are dependent on LIST_OF_TIMES_FROM_DATABASE
and it's also not in sequence,
And you are expecting it to execute in the sequence,
1) First, it will execute all the thing which is outside the useEffect and it's dependency whenever there is change in state, so keep that in mind
2) useEffect(() => {...},[]) this will get called as soon as component mounts, so in most cases, you will get listOfTimes as [], because at that time API call might be in requesting data from server.
3) There are few unnecessary things like const [counts, setCounts] = useState({}) and useEffect(() => {...} , []), this is kind of overuse of functionality.
Sometimes you can do the things simply but with all these it becomes complicated
Solution :
So what you can do is just put all the code inside displayListOfTimes function and check for LIST_OF_TIMES_FROM_DATABASE if available then and only then proceed with steps 3,4,5. So you will never get LIST_OF_TIMES_FROM_DATABASE undefined
NOTE : And as per the code LIST_OF_TIMES_FROM_DATABASE either be blank
array or array with data but never undefined, and if you are getting undefined then you can check that while setting up the state
const weekday = moment().isoWeekday()
export const TimeGrid = () => {
const { userObject } = useContext(Context)
//(1) I wish to use the below to generate a list of times
const [LIST_OF_TIMES_FROM_DATABASE, SET_LIST_OF_TIMES_FROM_DATABASE] = useState([])
let businessId
function getBusinessId() {
if (userObject) businessId = userObject.businessId
}
getBusinessId()
//defines function that will run below inside of first useEffect
//also where the list of times is supposed to be set
function getWorkingHoursAccordingToDayOfTheWeek(day, snapshot) {
const workingHours = []
const ALL_AVAILABLE_TIMES = []
workingHours.push(snapshot.data().beginWeek)
workingHours.push(snapshot.data().endWeek)
const [begin, ending] = workingHours
let bgn = moment(begin, 'HH:mm')
const end = moment(ending, 'HH:mm')
let i = 0
while (bgn <= end) {
ALL_AVAILABLE_TIMES.push({
id: i,
type: 'time',
day: 'today',
time: bgn.format('HHmm'),
})
bgn = bgn.add(30, 'minutes')
i++
}
SET_LIST_OF_TIMES_FROM_DATABASE(ALL_AVAILABLE_TIMES) //(2) This is where I set the list, which won't work on its 1st run
}
useEffect(() => {
async function getTimesFromDB() {
const approved = await approvedBusinessService.doc(businessId)
const snapshotApproved = await approved.get()
if (snapshotApproved.exists) {
getWorkingHoursAccordingToDayOfTheWeek(weekday, snapshotApproved)
return
} else {
const pending = await businessPendingApprovalService.doc(businessId)
const snapshotPending = await pending.get()
if (snapshotPending.exists) {
getWorkingHoursAccordingToDayOfTheWeek(weekday, snapshotPending)
}
}
return
}
getTimesFromDB()
}, [userObject])
const displayListOfTimes = () => { // <----- Start - HERE
if(LIST_OF_TIMES_FROM_DATABASE && LIST_OF_TIMES_FROM_DATABASE.length) {
const counts = {}
const allBookedTimes = allBookings.map(element => element.time)
//(3) ------ this will never be undefined
const listOfTimes = LIST_OF_TIMES_FROM_DATABASE.map(item => item.time)
//(4) ------ now it will work always
listOfTimes.forEach(x => {
counts[x] = (counts[x] || 0) + 1
if (allBookedTimes.includes(x)) counts[x] = counts[x] - 1
})
//(5) ------ now it will work
const sortedListOfTimesAndCount = Object.keys(counts).sort()
return sortedListOfTimesAndCount.map(
time =>
time > currentTime && (
<>
<li>
{time}
</li>
</>
),
)
} else {
return <li>Nothing to show for now</li>
}
}
return (
<div>
<ul>{displayListOfTimes}</ul>
</div>
)
}
The problem is because you useEffect which uses listOfTimes isn't being called when the listOfTimes value updates after a fetch request.
You can define listOfTimes within the useEffect and add a dependency on LIST_OF_TIMES_FROM_DATABASE
const [counts, setCounts] = useState({})
useEffect(() => {
// Defining it inside because if we don't and add allBookedTimes as a dependency then it will lead to an infinite look since references will change on each re-render
const allBookedTimes = allBookings.map(element => element.time)
const listOfTimes = LIST_OF_TIMES_FROM_DATABASE.map(item => item.time)
const counts = {}
listOfTimes.forEach(x => {
counts[x] = (counts[x] || 0) + 1
if (allBookedTimes.includes(x)) counts[x] = counts[x] - 1
})
setCounts(counts)
}, [LIST_OF_TIMES_FROM_DATABASE, allBookings]); // Add both dependencies. This will ensure that you update counts state when the state for times changes

React Hook not setting with useEffect

I'm using useEffect to fetch some data from Trello and set some states. First I grab the card I'm looking for and call setCard and setCardLocation. Everything is working fine. Then I get into my else case and no matter what I do setPublishDate will never be set, the loop continues to run. Why do all of these other hooks work but my last one doesn't? Thanks.
export default function Home(props) {
const [performedFetch, setPerformedFetch] = useState(false);
const [slug, setSlug] = useState(null);
const [cardLocation, setCardLocation] = useState(1);
const [card, setCard] = useState(null);
const [publishDate, setPublishDate] = useState(null);
const key = ''; // imagine these are here
const token = '';
useEffect(() => {
setSlug(
new URLSearchParams(window.location.search).get('slug')
);
if (!performedFetch && !!slug) {
fetch(`https://api.trello.com/1/lists/${listId}/cards?key=${key}&token=${token}`)
.then(response => response.json())
.then(data => {
setPerformedFetch(true);
data.forEach((c, index) => {
if (c.desc.includes(slug)) {
setCard(c)
setCardLocation(index + 1)
} else if (!publishDate && index > cardLocation) {
console.log(publishDate); // why is this always null?? also runs multiple times
const name = c.name;
const frontHalf = name.split("/")[0].split(" ");
const month = frontHalf[frontHalf.length - 1];
const day = name.split("/")[1].split(")")[0];
setPublishDate(`${month}/${day}`);
}
});
});
}
});
As already mentioned by #TaghiKhavari, you should have two useEffects (Multiple effects to separate concerns).
Also, it is important to optimize the performance by skipping effects by providing a dependency array as second argument to the useEffect. So the effect will only re-run if any of its dependencies would change.
First effect for slug:
useEffect(() => {
setSlug(
new URLSearchParams(window.location.search).get('slug')
);
}, []) // Note: Remove "[]" if you want to set slug at each update / render Or keep it if you want to set it only once (at mount)
Second effect to fetch and set card and other details:
useEffect(() => {
if (!performedFetch && slug) {
fetch(
`https://api.trello.com/1/lists/${listId}/cards?key=${key}&token=${token}`
)
.then((response) => response.json())
.then((data) => {
setPerformedFetch(true)
// Note: if there can be only ONE matching card
const index = data.findIndex((card) => card.desc.includes(slug))
if (index > -1) {
const card = data[index]
setCard(card)
setCardLocation(index + 1)
const name = card.name
const frontHalf = name.split('/')[0].split(' ')
const month = frontHalf[frontHalf.length - 1]
const day = name.split('/')[1].split(')')[0]
setPublishDate(`${month}/${day}`)
}
// Setting State in a LOOP? is a problem
/*
data.forEach((card, index) => {
if (card.desc.includes(slug)) {
setCard(card)
setCardLocation(index + 1)
} else if (!publishDate && index > cardLocation) {
const name = card.name
const frontHalf = name.split('/')[0].split(' ')
const month = frontHalf[frontHalf.length - 1]
const day = name.split('/')[1].split(')')[0]
setPublishDate(`${month}/${day}`)
}
})*/
})
}
}, [slug, performedFetch])
Set states may be async to improve performance:
So, you should not set states in a loop as you are doing currently. If you must iterate through a loop and set all or few elements of the array in state, you can loop through the array and push all relevant items in a local array variable and set it to state after loop ends. Hope it helps!
It's because usually react states updates asynchronously and at the time you're checking for slug it hasn't set yet
you need to do something like this:
function Home(props) {
const [performedFetch, setPerformedFetch] = useState(false);
const [slug, setSlug] = useState(null);
const [cardLocation, setCardLocation] = useState(1);
const [card, setCard] = useState(null);
const [publishDate, setPublishDate] = useState(null);
const key = ""; // imagine these are here
const token = "";
useEffect(() => {
setSlug(new URLSearchParams(window.location.search).get("slug"));
});
useEffect(() => {
console.log(slug)
if (!performedFetch && !!slug) {
fetch(`https://api.trello.com/1/lists/${listId}/cards?key=${key}&token=${token}`)
.then(response => response.json())
.then(data => {
setPerformedFetch(true);
data.forEach((c, index) => {
if (c.desc.includes(slug)) {
setCard(c)
setCardLocation(index + 1)
} else if (!publishDate && index > cardLocation) {
console.log(publishDate); // why is this always null?? also runs multiple times
const name = c.name;
const frontHalf = name.split("/")[0].split(" ");
const month = frontHalf[frontHalf.length - 1];
const day = name.split("/")[1].split(")")[0];
setPublishDate(`${month}/${day}`);
}
});
});
}
}, [slug, performedFetch])
}

How to querying and aggregate multiple collection in Firebase

I need to retrieve a monthly work orders collection by project and list of users (in the month I could have some project's OdL hours not included in the users list and the users could have some OdL of other projects).
The OdL model contains the strings for project (projectCode) and user (userId).
I send to the service the dates in Timestamp format, the code of the project and an array with users list.
this.loadGantt(from: Timestamp, to: Timestamp, projectCode: string, users: string[]){...}
I tried to execute single queries, one for project code and one for single user.
These are the queries of the service:
this.docs = this.afs.collection<OdlModel>('odl', ref => {
return ref.where('projectCode', '==', project)
.where('date', '>=', from)
.where('date', '<=', to)
.orderBy('date', 'asc');
})
.snapshotChanges().pipe(map(coll => {
return coll.map(doc => ({ id: doc.payload.doc.id, ...doc.payload.doc.data()}));
}));
return this.docs;
this.docs = this.afs.collection<OdlModel>('odl', ref => {
return ref.where('userId', '==', user)
.where('date', '>=', from)
.where('date', '<=', to)
.orderBy('date', 'asc');
})
.snapshotChanges().pipe(map(coll => {
return coll.map(doc => ({ id: doc.payload.doc.id, ...doc.payload.doc.data()}));
}));
return this.docs;
This is the solution that I found:
loadGantt() {
const momentDate: Moment = moment(new Date());
this.firstDay = momentDate.startOf('month').toDate();
this.lastDay = momentDate.endOf('month').toDate();
const from = firebase.firestore.Timestamp.fromDate(this.firstDay);
const to = firebase.firestore.Timestamp.fromDate(this.lastDay);
this.odl = [];
const odlArray = [];
const a$ = this.odlService.getProjectOdlCollection(from, to, 'IGNC0954-IMI-19');
odlArray.push(a$);
this.user.forEach(u => {
const b$ = this.odlService.getUserOdlCollection(from, to, u);
odlArray.push(b$);
});
const result$ = combineLatest([odlArray]);
result$.subscribe(res => {
res.map(r => {
r.subscribe(odl => {
odl.forEach(o => {
const index = this.odl.findIndex(x => x.id === o.id);
if (index === -1) {
this.odl.push(o);
}
});
});
});
});
}
How to I get all data in a single Observable object?
Below is a snippet which shows how to combine two or more Firestore collections from AngularFire into a single Observable object.
Link here
Data Structure
const usersRef = this.afs.collection('users');
const fooPosts = usersRef.doc('userFoo').collection('posts').valueChanges();
const barPosts = usersRef.doc('userBar').collection('posts').valueChanges();
Solution
import { combineLatest } from 'rxjs/observable/combineLatest';
const combinedList = combineLatest<any[]>(fooPosts, barPosts).pipe(
map(arr => arr.reduce((acc, cur) => acc.concat(cur) ) ),
)
Also this example may also help with your issue.
Let me know if this was helpful.

Categories

Resources