I have this chunk of code:
export default function CloseInquiryComponent(props) {
const auth = getAuth();
const db = getFirestore();
const { id } = useParams();
const [someVar, setSomeVar] = useState("");
// get user
const [user, authLoading, authErr] = useAuthState(auth);
// get user data of a collection
const [userData, userDataLoading, dataErr] = useDocumentData(
user ? doc(db, `users/${user.uid}`) : null,
);
// get the inquiry data
const [inquiry, inquiryLoading, inquiryError] = useDocumentData(doc(db, "תקלות", id));
// show loading until data is done loading
if(inquiryLoading)
{
return <LoadingComponent/>
}
// this causes an error because there is a return before it.
setSomeVar(inquiry.SomeData);
If I remove the if statement and try to set there, it might be null. If I try something like:
if(!inquiryLoading)
{
setSomeVar(inquiry.SomeData);
return <pagehtmlhere/>
}
I get an error "too many re-renders".
each re-render calls the function and sets the variable, which causes more re-renders.
How can I set the data once it's been loaded, while also keeping the react rules in mind?
CodePudding user response:
Use useEffect
hook.
useEffect(() => {
if (inquiryLoading && inquiry) setSomeVar(inquiry.SomeData);
}, [inquiryLoading, inquiry])