I am in my final steps of placing my react web app on the internet, everything works fine on my localhost, but as soon as I place it on the internet, I get the error below.
Uncaught TypeError: Object(...) is not a function
y AuthProvider.js:64
React 12
80 index.js:8
u (index):1
t (index):1
r (index):1
<anonymous> main.9b7fd734.chunk.js:1
AuthProvider.js:64:36
y AuthProvider.js:64
React 12
80 index.js:8
u (index):1
t (index):1
r (index):1
<anonymous> main.9b7fd734.chunk.js:1
I do not know what I am doing wrong, I read everything multiple times.
This is the component where the error is. From what I can tell from the error, the error is in the function setSession.
import { createContext, useState, useMemo, useEffect, useCallback, useContext } from "react";
import config from '../config.json';
import * as usersApi from '../api/users';
import * as api from "../api";
const JWT_TOKEN_KEY = config.token_key;
const AuthContext = createContext();
function parseJwt(token) {
if (!token) return {};
const base64url = token.split('.')[1];
const payload = Buffer.from(base64url, 'base64');
const jsonPayload = payload.toString('ascii');
return JSON.parse(jsonPayload);
}
function parseExp(exp) {
if (!exp) return null;
if (typeof exp !== 'number') exp = Number(exp);
if(isNaN(exp)) return null;
return new Date(exp * 1000);
}
const useAuth = () => useContext(AuthContext);
export const useSession = () => {
const { loading, error, token, user, ready, hasRole } = useAuth();
return { loading,
error,
token,
user,
ready,
isAuthed: Boolean(token),
hasRole,
};
}
export const useLogin = () => {
const { login } = useAuth();
return login;
}
export const useLogout = () => {
const { logout } = useAuth();
return logout;
}
export const useRegister = () => {
const { register } = useAuth();
return register;
}
export const AuthProvider = ({
children
}) => {
const [ready, setReady] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [token, setToken] = useState(localStorage.getItem(JWT_TOKEN_KEY));
const [user, setUser] = useState(null);
const setSession = useCallback(async (token, user) => {
const { exp, userId } = parseJwt(token);
const expiry = parseExp(exp);
const stillValid = expiry >= new Date();
if (stillValid) {
localStorage.setItem(JWT_TOKEN_KEY, token);
} else {
localStorage.removeItem(JWT_TOKEN_KEY);
token = null;
}
api.setAuthToken(token);
setToken(token);
setReady(token && stillValid);
if (!user && stillValid) {
user = await usersApi.getById(userId);
}
setUser(user);
}, []);
useEffect(() => {
setSession(token, null);
}, [setSession, token]);
const login = useCallback( async (email, password) => {
try {
setError('');
setLoading(true);
const {token, user} = await usersApi.login(email, password);
await setSession(token, user);
return true;
} catch (error) {
setError(error);
return false;
} finally {
setLoading(false);
}
}, [setSession]);
const logout = useCallback(() => {
setSession(null, null);
}, [setSession]);
const register = useCallback( async ({name, email, password}) => {
try {
setError('');
setLoading(true);
const {token, user} = await usersApi.register({name, email, password});
await setSession(token, user);
return true;
} catch (error) {
setError(error);
return false;
} finally {
setLoading(false);
}
}, [setSession]);
const hasRole = useCallback((role) => {
if (!user) return false;
return user.roles.includes(role);
}, [user])
const value = useMemo(() => ({
loading,
error,
token,
user,
ready,
login,
logout,
register,
hasRole,
}), [loading, error, token, user, ready, login, logout, register, hasRole]);
return(
<AuthContext.Provider value={value}>
{children}
</AuthContext.Provider>
);
};
This is the function usersApi.getById(userId).
export const getById = async (id) => {
const { data } = await axios.get(`/users/${id}`);
return data;
}
Every thing I get from an api, is an api that works fine and is running op Heroku.
Change this
import { useCallback, useContext } from "react/cjs/react.development";
with this
import { useCallback, useContext } from "react";
It works on the localhost because you're importing the React Hook from the local node modules file. Because there is no local node modules file in the deployment, it gives an error for importing.
Related
When I load my Nextjs page, I get this error message: "Error: Rendered more hooks than during the previous render."
If I add that if (!router.isReady) return null after the useEffect code, the page does not have access to the solutionId on the initial load, causing an error for the useDocument hook, which requires the solutionId to fetch the document from the database.
Therefore, this thread does not address my issue.
Anyone, please help me with this issue!
My code:
const SolutionEditForm = () => {
const [formData, setFormData] = useState(INITIAL_STATE)
const router = useRouter()
const { solutionId } = router.query
if (!router.isReady) return null
const { document } = useDocument("solutions", solutionId)
const { updateDocument, response } = useFirestore("solutions")
useEffect(() => {
if (document) {
setFormData(document)
}
}, [document])
return (
<div>
// JSX code
</div>
)
}
useDocument hook:
export const useDocument = (c, id) => {
const [document, setDocument] = useState(null)
const [isLoading, setIsLoading] = useState(true)
const [error, setError] = useState(null)
useEffect(() => {
const ref = doc(db, c, id)
const unsubscribe = onSnapshot(
ref,
(snapshot) => {
setIsLoading(false)
if (snapshot.data()) {
setDocument({ ...snapshot.data(), id: snapshot.id })
setError(null)
} else {
setError("No such document exists")
}
},
(err) => {
console.log(err.message)
setIsLoading(false)
setError("failed to get document")
}
)
return () => unsubscribe()
}, [c, id])
return { document, isLoading, error }
}
You cannot call a hook, useEffect, your custom useDocument, or any other after a condition. The condition in your case is this early return if (!router.isReady) returns null. As you can read on Rules of Hooks:
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...
Just remove that if (!router.isReady) returns null from SolutionEditForm and change useDocument as below.
export const useDocument = (c, id) => {
const [document, setDocument] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
if (!id) return; // if there is no id, do nothing ๐๐ฝ
const ref = doc(db, c, id);
const unsubscribe = onSnapshot(
ref,
(snapshot) => {
setIsLoading(false);
if (snapshot.data()) {
setDocument({ ...snapshot.data(), id: snapshot.id });
setError(null);
} else {
setError("No such document exists");
}
},
(err) => {
console.log(err.message);
setIsLoading(false);
setError("failed to get document");
}
);
return () => unsubscribe();
}, [c, id]);
return { document, isLoading, error };
};
The if (!router.isReady) return null statement caused the function to end early, and subsequent hooks are not executed.
You need to restructure your hooks such that none of them are conditional:
const [formData, setFormData] = useState(INITIAL_STATE)
const router = useRouter()
const { solutionId } = router.query
const { document } = useDocument("solutions", solutionId, router.isReady) // pass a flag to disable until ready
const { updateDocument, response } = useFirestore("solutions")
useEffect(() => {
if (document) {
setFormData(document)
}
}, [document])
// Move this to after the hooks.
if (!router.isReady) return null
and then to make useDocument avoid sending extra calls:
export const useDocument = (c, id, enabled) => {
and updated the effect with a check:
useEffect(() => {
if (!enabled) return;
const ref = doc(db, c, id)
const unsubscribe = onSnapshot(
ref,
(snapshot) => {
setIsLoading(false)
if (snapshot.data()) {
setDocument({ ...snapshot.data(), id: snapshot.id })
setError(null)
} else {
setError("No such document exists")
}
},
(err) => {
console.log(err.message)
setIsLoading(false)
setError("failed to get document")
}
)
return () => unsubscribe()
}, [c, id, enabled])
UseEffect cannot be called conditionally
UseEffect is called only on the client side.
If you make minimal representation, possible to try fix this error
My component is listening to firestore through server sent events
'use client';
import styles from './Messages.module.scss';
import React, { useState, useContext, useEffect } from 'react';
import Message from '../Message/Message';
import { ChatContext } from '#/context/ChatContext';
import { useMessages } from '#/hooks/useMessages';
import { MessageData } from '#/typedef';
export default function Messages() {
const [messages, setMessages] = useState<Array<MessageData>>([]);
const { data: chatContextData } = useContext(ChatContext);
const slug = chatContextData.chatId ? chatContextData.chatId : '';
const encodedSlug = encodeURIComponent(slug);
const { isLoading } = useMessages(chatContextData.chatId || '', Boolean(chatContextData.chatId));
useEffect(() => {
if (!encodedSlug) {
return;
}
const eventSource = new EventSource(`/api/messages?chatId=${encodedSlug}`);
eventSource.onmessage = (event) => {
const message = JSON.parse(event.data);
setMessages(message?.chats?.messages);
};
return () => {
eventSource.close();
};
}, [encodedSlug]);
return (
<div className={styles.messages}>
{isLoading && <p>Loading...</p>}
{messages?.map((message: MessageData) => (
<Message message={message} key={message.id} />
))}
</div>
);
}
I am using swr to handle my api
import useSWR from 'swr';
const fetcher = async (url: string) => {
const res = await fetch(url);
return res.json();
};
export const useMessages = (slug: string, shouldFetch: boolean) => {
const encodedSlug = encodeURIComponent(slug);
const { data, isLoading, error, mutate } = useSWR(
shouldFetch ? `/api/messages/?chatId=${encodedSlug}` : null,
fetcher
);
return {
data,
isLoading,
error,
mutate
};
};
Below is my api
import { database } from '#/utils/firebase';
import type { NextApiRequest, NextApiResponse } from 'next';
const handler = async (req: NextApiRequest, res: NextApiResponse<FirebaseFirestore.DocumentData>) => {
res.setHeader('Content-Type', 'text/event-stream');
if (req.method === 'GET') {
const chatId = req.query.chatId;
try {
const chatRef = database.collection('chats').doc(chatId as string);
const chatData = await chatRef.get();
if (!chatData.exists) {
return res.status(404).json({ error: 'Chat not found' });
}
// send the initial data
res.write(`data: ${JSON.stringify({ chats: chatData.data() })}\n\n`);
// listen to updates and send to the connected client
let unsubscribe: () => void;
const sendMessage = (chatData: FirebaseFirestore.DocumentData) => {
res.write(`data: ${JSON.stringify({ chats: chatData })}\n\n`);
};
unsubscribe = chatRef.onSnapshot((doc) => {
if (doc.exists) {
const chatData = doc.data() as FirebaseFirestore.DocumentData;
sendMessage(chatData);
}
});
// remove the listener when the client disconnects
req.on('close', () => {
unsubscribe();
});
res.statusCode = 200;
res.end();
} catch (error) {
console.error(error);
return res.status(500).json({ error: 'Error retrieving Chat' });
}
}
};
export default handler;
However, when I switch tabs or even close my laptop, I can see that a request to my api is being sent. It never stops. I even killed the dev server and the server sent events still seem to be going. It's been 10 minutes and I've sent around 1000 read requests to firestore.
How do I close my event source connection? Why is my firestore still being sent read requests? My application is not public so I have no idea where all these read requests are coming from.
In many components, I need to fetch some data and I'm ending up with a lot of similar code. It looks like this:
const [data, setData] = useState();
const [fetchingState, setFetchingState] = useState(FetchingState.Idle);
useEffect(
() => {
loadDataFromServer(props.dataId);
},
[props.dataId]
);
async function loadDataFromServer(id) {
let url = new URL(`${process.env.REACT_APP_API}/data/${id}`);
let timeout = setTimeout(() => setFetchingState(FetchingState.Loading), 1000)
try {
const result = await axios.get(url);
setData(result.data);
setFetchingState(FetchingState.Idle);
}
catch (error) {
setData();
setFetchingState(FetchingState.Error);
}
clearTimeout(timeout);
}
How can I put it into a library and reuse it?
Thank you guys for the suggestion, I came up with the following hook. Would be happy to some critics.
function useFetch(id, setData) {
const [fetchingState, setFetchingState] = useState(FetchingState.Idle);
useEffect(() => { loadDataFromServer(id); }, [id]);
async function loadDataFromServer(id) {
let url = new URL(`${process.env.REACT_APP_API}/data/${id}`);
let timeout = setTimeout(() => setFetchingState(FetchingState.Loading), 1000)
try {
const result = await axios.get(url);
setData(result.data);
setFetchingState(FetchingState.Idle);
}
catch (error) {
setData();
setFetchingState(FetchingState.Error);
}
clearTimeout(timeout);
}
return fetchingState;
}
And this is how I use it:
function Thread(props) {
const [question, setQuestion] = useState();
const fetchingState = useFetch(props.questionId, setQuestion);
if (fetchingState === FetchingState.Error) return <p>Error while getting the post.</p>;
if (fetchingState === FetchingState.Loading) return <Spinner />;
return <div>{JSON.stringify(question)}</div>;
}
You can wrap your APIs calls in /services folder and use it anywhere
/services
- Auth.js
- Products.js
- etc...
Example
Auth.js
import Axios from 'axios';
export const LoginFn = (formData) => Axios.post("/auth/login", formData);
export const SignupFn = (formData) => Axios.post("/auth/signup", formData);
export const GetProfileFn = () => Axios.get("/auth/profile")
in your component
import React, { useState } from 'react'
import { LoginFn } from '#Services/Auth'
export LoginPage = () => {
const [isLoading, setIsLoading] = useState(false);
const LoginHandler = (data) => {
setIsLoading(true)
LoginFn(data).then(({ data }) => {
// do whatever you need
setIsLoading(false)
})
}
return (
<form onSubmit={LoginHandler}>
.......
)
}
I'm new to react native, I have a personal project, I am trying to get data from Firestore cloud, but I keep getting this error on the screen change.
It works fine when I comment out the database code, so I'm wondering what could be the cause.
My code
import React from "react";
import auth from "#react-native-firebase/auth";
import firestore from "#react-native-firebase/firestore";
const ProfileStackScreen = ({ navigation }) => {
React.useEffect(() => {
const usr = auth().currentUser;
setuserData(prev => {
return { ...prev, uid: usr.uid };
});
}, []);
const userRef = firestore().collection("users");
const snapshot = userRef
.where("uid", "==", userData.uid)
.onSnapshot()
.then(console.log(uid))
.catch(error => {
Alert.alert(error.message);
});
const [userData, setuserData] = React.useState({
uid: ""
// other field go here
});
return (
<View>
<Text>{userData.uid}</Text>
</View>
);
};
export default ProfileStackScreen;
You can try below code
import React from 'react';
import auth from '#react-native-firebase/auth';
import firestore from '#react-native-firebase/firestore';
const ProfileStackScreen = ({ navigation }) => {
React.useEffect(() => {
const usr = auth().currentUser;
setuserData((prev)=>{
return {...prev,uid: usr.uid};
});
}, []);
React.useEffect(() => {
fetchdata()
}, [userData]);// Once userData value has been updated then only call fetchData()
const fetchdata = ()=>{
const userRef = firestore().collection('users').doc(userData.uid).get()
.then(function (doc) {
if (doc.exists) {
console.log("Document found!");
console.log(doc.data())
} else {
console.log("No such document!");
}
});
}
const [userData, setuserData] = React.useState({
uid: '',
// other field go here
});
return (
<View>
<Text>{userData.uid}</Text>
</View>
);
};
export default ProfileStackScreen;
#Maheshvirus is right. But I think you have tried to fetch data when userData.uid is not empty.
Try this way if looking for such a way.
import React from 'react';
import auth from '#react-native-firebase/auth';
import firestore from '#react-native-firebase/firestore';
const ProfileStackScreen = ({ navigation }) => {
React.useEffect(() => {
const usr = auth().currentUser;
setuserData((prev)=> {
return {...prev,uid: usr.uid};
});
}, []);
React.useEffect(() => {
if(userData.uid !== ''){
getData()
}
}, [userData]);
const getData = () => {
firestore()
.collection('users');
.where('uid', '==', userData.uid)
.onSnapshot()
.then(() => {
console.log(uid)
})
.catch((error)=> {
Alert.alert(error.message);
});
}
const [userData, setuserData] = React.useState({
uid: '',
// other field go here
});
return (
<View>
<Text>{userData.uid}</Text>
</View>
);
};
export default ProfileStackScreen;
I'm trying to render a header.
First, in InnerList.js, I make an API call, and with the data from the API call, I set a list in context.
Second, in Context.js, I take the list and set it to a specific data.
Then, in InnerListHeader.js, I use the specific data to render within the header.
Problem: I currently get a TypeError undefined because the context is not set before rendering. Is there a way to wait via async or something else for the data to set before loading?
My code block is below. I've been looking through a lot of questions on StackOverflow and blogs but to no avail. Thank you!
InnerList.js
componentDidMount() {
const { dtc_id } = this.props.match.params;
const {
setSpecificDtcCommentList,
} = this.context;
MechApiService.getSpecificDtcCommentList(dtc_id)
.then(res =>
setSpecificDtcCommentList(res)
)
}
renderSpecificDtcCommentListHeader() {
const { specificDtc = [] } = this.context;
return (
<InnerDtcCommentListItemHeader key={specificDtc.id} specificDtc={specificDtc} />
)
}
Context.js
setSpecificDtcCommentList = (specificDtcCommentList) => {
this.setState({ specificDtcCommentList })
this.setSpecificDtc(specificDtcCommentList)
}
setSpecificDtc = (specificDtcCommentList) => {
this.setState({ specificDtc: specificDtcCommentList[0] })
}
InnerListHeader.js
render() {
const { specificDtc } = this.props;
return (
<div>
<div className="InnerDtcCommentListItemHeader__comment">
{specificDtc.dtc_id.dtc}
</div>
</div>
);
}
In general, you should always consider that a variable can reach the rendering stage without a proper value (e.g. unset). It is up to you prevent a crash on that.
For instance, you could rewrite you snippet as follows:
render() {
const { specificDtc } = this.props;
return (
<div>
<div className="InnerDtcCommentListItemHeader__comment">
{Boolean(specificDtc.dtc_id) && specificDtc.dtc_id.dtc}
</div>
</div>
);
}
When you make an api call you can set a loader while the data is being fetched from the api and once it is there you show the component that will render that data.
In your example you can add a new state that will pass the api call status to the children like that
render() {
const { specificDtc, fetchingData } = this.props;
if (fetchingData){
return <p>Loading</p>
}else{
return (
<div>
<div className="InnerDtcCommentListItemHeader__comment">
{specificDtc.dtc_id.dtc}
</div>
</div>
);
}
}
``
in my case, i am calling external api to firebase which lead to that context pass undefined for some values like user. so i have used loading set to wait untile the api request is finished and then return the provider
import { createContext, useContext, useEffect, useState } from 'react';
import {
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
signOut,
onAuthStateChanged,
GoogleAuthProvider,
signInWithPopup,
updateProfile
} from 'firebase/auth';
import { auth } from '../firebase';
import { useNavigate } from 'react-router';
import { create_user_db, get_user_db } from 'api/UserAPI';
import { CircularProgress, LinearProgress } from '#mui/material';
import Loader from 'ui-component/Loader';
const UserContext = createContext();
export const AuthContextProvider = ({ children }) => {
const [user, setUser] = useState();
const [user_db, setUserDB] = useState();
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [loading, setLoading] = useState(true);
const navigate = useNavigate();
const createUser = async (email, password) => {
const user = await createUserWithEmailAndPassword(auth, email, password);
};
const signIn = (email, password) => {
return signInWithEmailAndPassword(auth, email, password)
.then(() => setIsAuthenticated(true))
.catch(() => setIsAuthenticated(false));
};
const googleSignIn = async () => {
const provider = new GoogleAuthProvider();
await signInWithPopup(auth, provider)
.then(() => setIsAuthenticated(true))
.catch(() => setIsAuthenticated(false));
};
const logout = () => {
setUser();
return signOut(auth).then(() => {
window.location = '/login';
});
};
const updateUserProfile = async (obj) => {
await updateProfile(auth.currentUser, obj);
return updateUser(obj);
};
const updateUser = async (user) => {
return setUser((prevState) => {
return {
...prevState,
...user
};
});
};
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, async (currentUser) => {
setLoading(true);
if (currentUser) {
const user_db = await get_user_db({ access_token: currentUser.accessToken });
setUserDB(user_db);
setUser(currentUser);
setIsAuthenticated(true);
}
setLoading(false);
});
return () => {
unsubscribe();
};
}, []);
if (loading) return <Loader />;
return (
<UserContext.Provider value={{ createUser, user, user_db, isAuthenticated, logout, signIn, googleSignIn, updateUserProfile }}>
{children}
</UserContext.Provider>
);
};
export const UserAuth = () => {
return useContext(UserContext);
};