I have a component that displays learning time from an api for the current user. each time the user view changes, contactInfo will have the data for the current user and it will trigger the useEffect.
export const Learning = () => {
// ... var declarations
async function getLearningData(obj) {
var params_oneWk = getParamsForLearningAvg(obj, 1);
var params_fourWk = getParamsForLearningAvg(obj, 4);
var params_12Wk = getParamsForLearningAvg(obj, 12);
setLastwkLoader(false);
setFourwkLoader(false);
setTwelvewkLoader(false);
const cachedData =
JSON.parse(localStorage.getItem("LearningTime")) || null;
const loggedUser =
JSON.parse(localStorage.getItem("loggedInUser")) || null;
if (
cachedData &&
loggedUser &&
loggedUser?.email === contactInfo?.email &&
params_oneWk.from === cachedData.from
) {
setLastwkLoader(true);
setOneWeekAvg(cachedData.week1);
setFourwkLoader(true);
setFourWeekAvg(cachedData.week4);
setTwelvewkLoader(true);
setTwelveWeekAvg(cachedData.week12);
return;
}
if (params_oneWk.user_email) {
let resp1 = await getLearningAvg(params_oneWk, 1, appurl);
setLastwkLoader(true);
setOneWeekAvg(resp1);
let resp2 = await getLearningAvg(params_fourWk, 4, appurl);
setFourwkLoader(true);
setFourWeekAvg(resp2);
let resp3 = await getLearningAvg(params_12Wk, 12, appurl);
setTwelvewkLoader(true);
setTwelveWeekAvg(resp3);
console.log("params_12Wk ", params_12Wk);
console.log("resp3 ", resp3);
if (loggedUser && params_oneWk.user_email == loggedUser.email) {
localStorage.setItem(
"LearningTime",
JSON.stringify({
week1: resp1,
week4: resp2,
week12: resp3,
from: params_oneWk.from,
})
);
}
}
}
useEffect(() => {
console.log("changing contactInfo");
getLearningData(contactInfo);
}, [contactInfo]);
};
The problem is that the api that fetches learning time is kinda slow and hence I'm caching it for the loggedIn user. Since caching data comes faster than that of the api, sometimes the api call gets resolved after the cachedData is shown on the UI and it overrides the currentData and shows wrong data. Why is the previous async function doesn't stop executing as soon as the dependency changes in the useEffect? Where am I going wrong?
I've created a application for my company to manage diffrent things.
I first started realizing it with Class-Components, now switched to Functional components.
The issue that i'm facing is, that in one function inside Websocket onMessage uses old/empty state.
This is how the application currently is built.
const DocumentControl = ({ createWebsocket, logOut }) => {
const [elementList, setElementList] = useState([]);
const webSocket = useRef(null);
useEffect(() => {
webSocket.current = createWebsocket();
webSocket.current.onmessage = (messageEvent) => {
console.log(elementList);
if (devComm) {
console.log(JSON.parse(messageEvent.data));
}
processMessage(JSON.parse(messageEvent.data));
};
window.addEventListener("beforeunload", () => {
logOut(true);
});
}, []);
useEffect(() => {
loadElements();
}, [menu]);
const processMessage = (message) => {
var newArr, index;
switch (message.type) {
case "document":
var elementItem = message.data;
newArr = [...elementList]; // here elementList is always []
...
break;
default:
if (devComm) {
console.log("---Unknown WSMessage!---");
}
}
};
}
There is obviously more logic but this may be sufficient to describe my problem.
Basically i'm loading from the Server my ElementList if the Menu changes.
Whenever an Element on the Server-Side is updated, I send a message through Websockets to all clients, so all are up-to-date.
---My Issue---
Loading the Elements from Server and using setElementList works fine. But whenever I receive a message through websockets, the state elementList is always empty.
I made a button which displays the current elementList and there the List is correctly.
For example: I have 4 Elements in my list. Because of Message in Websockets i want to add to my current list the new Element. But the elementList is [] inside processMessage, so I add the new element to an [] and after setElementList all other elements are gone (because of empty array previously)
My first thought was, that (because I get the Websocket element from parent) maybe it uses diffrent instance of elementList, which is initialized as empty [].
But it would not make sense, because setElementList still affects the "original" elementList.
I also tried using elementList with useRef(elementList) and accessing it with ref.current but still didn't change the outcome.
here is how the createWebsocket is implemented:
const createWebsocket = () => {
if (!webSocket.current) {
var uri = baseURI.replace("http://", "ws://");
console.log("Create new Websocket");
console.log("Websocket: " + uri + "websocket/");
let socket = new WebSocket(uri + "websocket/" + user.Token);
socket.onopen = () => {};
socket.onclose = (closeEvent) => {
console.log("closed socket:");
if (closeEvent.code !== 3001) {
logOut(false);
if (closeEvent !== null && closeEvent.reason.length > 0) {
alert(closeEvent.reason);
}
}
};
socket.onerror = () => {
logOut(true, false);
alert("Something went wrong");
};
webSocket.current = socket;
}
return webSocket.current;
};
Any Ideas why elementList is diffrent inside ProcessMessage then in other functions of the Component?
--------- UPDATE -------
I could temporary fix it, by using this workaround:
const elementsRef = useRef([]);
useEffect(() => {
elementsRef.current = elementList;
}, [elementList]);
and then accessing elementsRef.current
But there must be an more elegant soltuion to this
I have this data from firestore and I wanted to retrieve it dynamically with a where() but this is the error I'm getting:
TypeError: vaccines is not a function
The user collection:
[![enter image description here][1]][1]
Below are the codes:
const Vaccine = () => {
const [vaccines, setVaccines] = useState([]);
useEffect(() => {
const unsubscribe = firestore
.collection("vaccines")
.onSnapshot((snapshot) => {
const arr = [];
snapshot.forEach((doc) =>
arr.push({
...doc.data(),
id: doc.id,
})
);
setVaccines(arr);
});
return () => {
unsubscribe();
};
}, []);
Preface
As highlighted in the comments on the original question, this query structure is not advised as it requires read access to sensitive user data under /users that includes private medical data.
DO NOT USE THIS CODE IN A PRODUCTION/COMMERICAL ENVIRONMENT. Failure to heed this warning will lead to someone suing you for breaches of privacy regulations.
It is only suitable for a school project (although I would a fail a student for such a security hole) or proof of concept using mocked data. The code included below is provided for education purposes, to solve your specific query and to show strategies of handling dynamic queries in React.
From a performance standpoint, in the worst case scenario (a cache miss), you will be billed one read, for every user with at least one dose of any vaccine, on every refresh, for every viewing user. Even though your code doesn't use the contents of any user document, your code must download all of this data too because the Client SDKs do not support the select() operator.
For better security and performance, perform this logic server-side (e.g. Cloud Function, a script on your own computer, etc) and save the results to a single document that can be reused by all users. This will allow you to properly tighten access to /users. It also significantly simplifies the code you need to display the graphs and live statistics on the client-side.
useEffect
As stated by the React documentation on the Rules of hooks:
Only Call Hooks at the Top Level
Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.
The documentation further elaborates that React relies on the order in which Hooks are called, which means that you can't have hook definitions behind conditional logic where their order and quantity changes between renders. If your hooks rely on some conditional logic, it must be defined inside of the hook's declaration.
As an example, if you have an effect that relies on other data, with this logic:
const [userProfile, setUserProfile] = useState();
const [userPosts, setUserPosts] = useState(null);
useEffect(() => {
// get user profile data and store in userProfile
}, []);
if (userProfile) {
useEffect(() => {
// get user post list and store in userPosts
}, [userProfile]);
}
you need to instead use:
const [userProfile, setUserProfile] = useState();
const [userPosts, setUserPosts] = useState(null);
useEffect(() => {
// get user profile data and store in userProfile
}, []);
useEffect(() => {
if (!userProfile) {
// not ready yet/signed out
setUserPosts(null);
return;
}
// get user post list and store in userPosts
}, [userProfile]);
Similarly, for arrays:
someArray && someArray.forEach((entry) => {
useEffect(() => {
// do something with entry to define the effect
}, /* variable change hooks */);
});
should instead be:
useEffect(() => {
if (!someArray) {
// not ready yet
return;
}
const cleanupFunctions = [];
someArray.forEach((entry) => {
// do something with entry to define an effect
cleanupFunctions.push(() => {
// clean up the effect
});
});
// return function to cleanup the effects created here
return () => {
cleanupFunctions.forEach(cleanup => cleanup());
}
}, /* variable change hooks */);
Because this looks a lot like lifecycle management, you are actually better off replacing it with nested components rather than using hooks, like so:
return (
<> // tip: React.Fragment shorthand (used for multiple top-level elements)
{
someArray && someArray
.map(entry => {
return <Entry key={entry.key} data={entry.data} />
})
}
</>
);
Adapting to your code
Note: The code here doesn't use onSnapshot for the statistics because it would cause a rerender every time a new user is added to the database.
const getVaccineStats = (vaccineName) => {
const baseQuery = firestore
.collection("users")
.where("doses.selectedVaccine", "==", vaccine);
const oneDoseQueryPromise = baseQuery
.where("doses.dose1", "==", true)
.where("doses.dose2", "==", false)
.get()
.then(querySnapshot => querySnapshot.size);
const twoDoseQueryPromise = baseQuery
.where("doses.dose1", "==", true)
.where("doses.dose2", "==", true)
.get()
.then(querySnapshot => querySnapshot.size);
return Promise.all([oneDoseQueryPromise, twoDoseQueryPromise])
.then(([oneDoseCount, twoDoseCount]) => ({ // tip: used "destructuring syntax" instead of `results[0]` and `results[1]`
withOneDose: oneDoseCount,
withTwoDoses: twoDoseCount
}));
};
const Vaccine = () => {
const [vaccines, setVaccines] = useState();
const [vaccineStatsArr, setVaccineStatsArr] = useState([]);
// Purpose: Collect vaccine definitions and store in `vaccines`
useEffect(() => {
return firestore // tip: you can return the unsubscribe function from `onSnapshot` directly
.collection("vaccines")
.onSnapshot({ // tip: using the Observer-like syntax, allows you to handle errors
next: (querySnapshot) => {
const vaccineData = []; // tip: renamed `arr` to indicate what the data contains
querySnapshot.forEach((doc) =>
vaccineData.push({
...doc.data(),
id: doc.id,
});
);
setVaccines(vaccineData);
}),
error: (err) => {
// TODO: Handle database errors (e.g. no permission, no connection)
}
});
}, []);
// Purpose: For each vaccine definition, fetch relevant statistics
// and store in `vaccineStatsArr`
useEffect(() => {
if (!vaccines || vaccines.length === 0) {
return; // no definitions ready, exit early
}
const getVaccineStatsPromises = vaccines
.map(({ vaccine }) => [vaccine, getVaccineStats(vaccine)]);
// tip: used "destructuring syntax" on above line
// (same as `.map(vaccineInfo => [vaccineInfo.vaccine, getVaccineStats(vaccineInfo.vaccine)]);`)
let unsubscribed = false;
Promise.all(getVaccineStatsPromises)
.then(newVaccineStatsArr => {
if (unsubscribed) return; // unsubscribed? do nothing
setVaccineStatsArr(newVaccineStatsArr);
})
.catch(err => {
if (unsubscribed) return; // unsubscribed? do nothing
// TODO: handle errors
});
return () => unsubscribed = true;
}, [vaccines]);
if (!vaccines) // not ready? hide element
return null;
if (vaccines.length === 0) // no vaccines found? show error
return (<span class="error">No vaccines found in database</span>);
if (vaccineStatsArr.length === 0) // no stats yet? show loading message
return (<span>Loading statistics...</span>);
return (<> // tip: React.Fragment shorthand
{
vaccineStatsArr.map(([name, stats]) => {
// this is an example component, find something suitable
// the `key` property is required
return (<BarGraph
key={name}
title={`${name} Statistics`}
columns={["One Dose", "Two Doses"]}
data={[stats.withOneDose, stats.withTwoDoses]}
/>);
});
}
</>);
};
export default Vaccine;
Live Statistics
If you want your graphs to be updated live, you need "zip together" the two snapshot listeners into one, similar to the rxjs combineLatest operator. Here is an example implementation of this:
const onVaccineStatsSnapshot => (vaccine, observerOrSnapshotCallback, errorCallback = undefined) => {
const observer = typeof observerOrCallback === 'function'
? { next: observerOrSnapshotCallback, error: errorCallback }
: observerOrSnapshotCallback;
let latestWithOneDose,
latestWithTwoDoses,
oneDoseReady = false,
twoDosesReady = false;
const fireNext = () => {
// don't actually fire event until both counts have come in
if (oneDoseReady && twoDosesReady) {
observer.next({
withOneDose: latestWithOneDose,
withTwoDoses: latestWithTwoDoses
});
}
};
const fireError = observer.error || (err) => console.error(err);
const oneDoseUnsubscribe = baseQuery
.where("doses.dose1", "==", true)
.where("doses.dose2", "==", false)
.onSnapshot({
next: (querySnapshot) => {
latestWithOneDose = querySnapshot.size;
oneDoseReady = true;
fireNext();
},
error: fireError
});
const twoDoseUnsubscribe = baseQuery
.where("doses.dose1", "==", true)
.where("doses.dose2", "==", true)
.onSnapshot({
next: (querySnapshot) => {
latestWithTwoDoses = querySnapshot.size;
twoDosesReady = true;
fireNext();
},
error: fireError
});
return () => {
oneDoseUnsubscribe();
twoDoseUnsubscribe();
};
}
You could rewrite the above function to make use of useState, but this would unnecessarily cause components to rerender when they don't need to.
Usage (direct):
const unsubscribe = onVaccineStatsSnapshot(vaccineName, {
next: (statsSnapshot) => {
// do something with { withOneDose, withTwoDoses } object
},
error: (err) => {
// TODO: error handling
}
);
or
const unsubscribe = onVaccineStatsSnapshot(vaccineName, (statsSnapshot) => {
// do something with { withOneDose, withTwoDoses } object
});
Usage (as a component):
const VaccineStatsGraph = (vaccineName) => {
const [stats, setStats] = useState(null);
useEffect(() => onVaccineStatsSnapshot(vaccineName, {
next: (newStats) => setStats(newStats),
error: (err) => {
// TODO: Handle errors
}
}, [vaccineName]);
if (!stats)
return (<span>Loading graph for {vaccineName}...</span>);
return (
<BarGraph
title={`${name} Statistics`}
columns={["One Dose", "Two Doses"]}
data={[stats.withOneDose, stats.withTwoDoses]}
/>
);
}
vaccines is an array and not a function. You are trying to run a map on vaccines. Try refactoring your code to this:
vaccines &&
vaccines.map((v, index) => {
// ...
})
Also do check: How to call an async function inside a UseEffect() in React?
here is the code, that works for you:
function DatafromFB() {
const[users, setUsers] = useState({});
useEffect(()=>{
const fetchVaccine = async () => {
try {
const docs = await db.collection("vaccines").get();;
docs.forEach((doc) => {
doc.data().vaccineDetails
.forEach(vaccineData=>{
fetchUsers(vaccineData.vaccine)
})
})
} catch (error) {
console.log("error", error);
}
}
const fetchUsers = async (vaccine)=>{
try {
const docs = await db.collection("users")
.where("doses.selectedVaccine", "==", vaccine).get();
docs.forEach(doc=>{
console.log(doc.data())
setUsers(doc.data());
})
}catch(error){
console.log("error", error);
}
}
fetchVaccine();
},[])
return (
<div>
<h1>{users?.doses?.selectedVaccine}</h1>
</div>
)
}
export default DatafromFB
what is ${index.vaccine} I think it must be v.vaccine
also setSize(snap.size); will set set size commonly not vaccine specific
I am coding a React app that fetches data from WordPress REST API. Everything works fine so far, however, loading indicator does not show up. I use MobX for state management. I have a loadingInitial observable. Whenever I start my action, I set this observable true to get into loading state. After the action does necessary operations, I reset loadingInitial to false. So I expect to see loading screen while fetching posts. But I see blank page while the daha is loading.
Here are the code for the action:
#action loadAnecdotes = async (page: number, year: number, order: string) => {
this.loadingInitial = true
try {
const anecdotesHeaders = year === 0 ? await agent.AnecdotesHeaders.list() : await agent.AnecdotesHeaders.listByYear(year)
const maxPages = anecdotesHeaders['x-wp-totalpages']
if (page <= maxPages) {
const anecdotes = year === 0 ? await agent.Anecdotes.list(page, order) : await agent.Anecdotes.listByYear(page, year, order)
runInAction(() => {
this.anecdoteArray = []
anecdotes.forEach((anecdote, i) => {
this.anecdoteArray[i] = anecdote
})
this.loadingInitial = false
})
} else {
runInAction(() => {
this.loadingInitial = false
})
}
return {anecdoteArray: this.anecdoteArray, maxPages}
} catch (error) {
console.log(error)
this.loadingInitial = false
}
}
Here is my useEffect in the component where I fetch the posts:
useEffect(() => {
loadAnecdotes(page, year, order).then(result => {
if (page <= result?.maxPages)
setArray(a => [...a, ...result?.anecdoteArray!])
setLoaded(true)
})
}, [loadAnecdotes, page, year, order, setLoaded, setArray])
Here is the what I call just before the returning the posts:
if (loadingInitial) return <LoadingComponent content='Anecdotes loading...' />
As a side note, my component is set as an observer.
What could I be doing wrong?
Well, it seems loadingInitial is not enough alone. I added a second condition to it, the length of the posts array. If it is 0, show the loading component. And it worked! Just this edit solves the problem:
if (loadingInitial || !array.length) return <LoadingComponent content='Anecdotes loading...' />
I am creating a small middleware for redux. Since my electron application connects to another database and updates it's state (so that I may see the state of this application on my main application). Here is my basic code:
const BLACKLIST = ['redux-form/FOCUS ', 'redux-form/BLUR'];
export remoteMiddleware => store => next => action => {
const db = MongoClient.connect(process.env.MONGO_URL);
try {
if (!BLACKLIST.includes(action.type)) {
const state = store.getState();
db.collection('state').update(
{ _id: process.env.APP_ID },
{ $set: { state } }
)
}
} finally {
db.close();
}
}
However, I am having a bit of a problem where this is firing TOO often, when it doesn't always need to fire immediately. I would prefer if it fired every n iterations, or perhaps no more than x ms.
Is there a way to throttle a redux middleware so that it will only fire every n times, or such that it will only run every x number of ms?
How about simply
const BLACKLIST = ['redux-form/FOCUS ', 'redux-form/BLUR'];
var lastActionTime = 0;
export remoteMiddleware => store => next => action => {
let now = Date.now();
try {
if (!BLACKLIST.includes(action.type) && now - lastActionTime > 100)
...
} finally() {
lastActionTime = now;
db.close();
}
}