React Context API state update leads to infinite loop - javascript

I am trying to add Authentication to my app and maintaining Auth State using React Context API.
I am calling my api using a custom hook use-http.
import { useCallback, useReducer } from 'react';
function httpReducer(state, action) {
switch (action.type) {
case 'SEND':
return {
data: null,
error: null,
status: 'pending',
};
case 'SUCCESS':
return {
data: action.responseData,
error: null,
status: 'completed',
};
case 'ERROR':
return {
data: null,
error: action.errorMessage,
status: 'completed',
};
default:
return state;
}
}
function useHttp(requestFunction, startWithPending = false) {
const [httpState, dispatch] = useReducer(httpReducer, {
status: startWithPending ? 'pending' : null,
data: null,
error: null,
});
const sendRequest = useCallback(
async requestData => {
dispatch({ type: 'SEND' });
try {
const responseData = await requestFunction(requestData);
dispatch({ type: 'SUCCESS', responseData });
} catch (error) {
dispatch({
type: 'ERROR',
errorMessage: error.response.data.message || 'Something went wrong!',
});
}
},
[requestFunction]
);
return {
sendRequest,
...httpState,
};
}
export default useHttp;
This is my Login page which calls the api and I need to navigate out of this page and also update my Auth Context.
import { useCallback, useContext } from 'react';
import { makeStyles } from '#material-ui/core';
import Container from '#material-ui/core/Container';
import LoginForm from '../components/login/LoginForm';
import useHttp from '../hooks/use-http';
import { login } from '../api/api';
import AuthContext from '../store/auth-context';
import { useEffect } from 'react';
const useStyles = makeStyles(theme => ({
pageWrapper: {
height: '100vh',
display: 'flex',
flexDirection: 'column',
backgroundColor: theme.palette.background.default,
},
pageContainer: {
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
flexGrow: '1',
},
}));
function Login() {
const authCtx = useContext(AuthContext);
const { sendRequest, status, data: userData, error } = useHttp(login);
const loginHandler = (email, password) => {
sendRequest({ email, password });
};
if (status === 'pending') {
console.log('making request');
}
if (status === 'completed' && userData) {
console.log('updateContext');
authCtx.login(userData);
}
if (status === 'completed' && error) {
console.log(error);
}
const classes = useStyles();
return (
<div className={classes.pageWrapper}>
<Container maxWidth="md" className={classes.pageContainer}>
<LoginForm status={status} onLoginHandler={loginHandler} />
</Container>
</div>
);
}
export default Login;
The login api -
export const login = async ({ email, password }) => {
let config = {
method: 'post',
url: `${BACKEND_URL}/api/auth/`,
headers: { 'Content-Type': 'application/json' },
data: {
email: email,
password: password,
},
};
const response = await axios(config);
return response.data;
};
The Auth Context -
import React, { useState } from 'react';
import { useEffect, useCallback } from 'react';
import {
getUser,
removeUser,
saveUser,
getExpirationTime,
clearExpirationTime,
setExpirationTime,
} from '../utils/local-storage';
const AuthContext = React.createContext({
token: '',
isLoggedIn: false,
login: () => {},
logout: () => {},
});
let logoutTimer;
const calculateRemainingTime = expirationTime => {
const currentTime = new Date().getTime();
const adjExpirationTime = new Date(expirationTime).getTime();
const remainingDuration = adjExpirationTime - currentTime;
return remainingDuration;
};
const retrieveStoredToken = () => {
const storedToken = getUser();
const storedExpirationDate = getExpirationTime();
const remainingTime = calculateRemainingTime(storedExpirationDate);
if (remainingTime <= 60) {
removeUser();
clearExpirationTime();
return null;
}
return {
token: storedToken,
duration: remainingTime,
};
};
export const AuthContextProvider = ({ children }) => {
const tokenData = retrieveStoredToken();
let initialToken = '';
if (tokenData) {
initialToken = tokenData.token;
}
const [token, setToken] = useState(initialToken);
const userIsLoggedIn = !!token;
const logoutHandler = useCallback(() => {
setToken(null);
removeUser();
clearExpirationTime();
if (logoutTimer) {
clearTimeout(logoutTimer);
}
}, []);
const loginHandler = ({ token, user }) => {
console.log('login Handler runs');
console.log(token, user.expiresIn);
setToken(token);
saveUser(token);
setExpirationTime(user.expiresIn);
const remainingTime = calculateRemainingTime(user.expiresIn);
logoutTimer = setTimeout(logoutHandler, remainingTime);
};
useEffect(() => {
if (tokenData) {
console.log(tokenData.duration);
logoutTimer = setTimeout(logoutHandler, tokenData.duration);
}
}, [tokenData, logoutHandler]);
const user = {
token,
isLoggedIn: userIsLoggedIn,
login: loginHandler,
logout: logoutHandler,
};
return <AuthContext.Provider value={user}>{children}</AuthContext.Provider>;
};
export default AuthContext;
The problem is when I call loginHandler function of my AuthContext in Login Component, the Login component re-renders and this login function goes in an infinite loop. What am I doing wrong?
I am new to React and stuck on this issue since hours now.

I think I know what it is.
You're bringing in a bunch of component state via hooks. Whenever authCtx, sendRequest, status, data and error change, the component re-renders. Avoid putting closures into the state. The closures trigger unnecessary re-renders.
function Login() {
const authCtx = useContext(AuthContext);
const { sendRequest, status, data: userData, error } = useHttp(login);
Try looking for all closures that could be causing re-renders and make sure components don't depend on them.
Edit:
Ben West is right- you also have side effects happening during the render, which is wrong.
When you have something like this in the body of a functional component:
if (status === 'completed' && userData) {
console.log('updateContext');
authCtx.login(userData);
}
Change it to this:
useEffect(() => {
if (status === 'completed' && userData) {
console.log('updateContext');
authCtx.login(userData);
}
}, [status, userData]); //the function in arg 1 is called whenever these dependencies change
I made a bunch of changes to your code:
It's down to 2 files. The other stuff I inlined.
I'm not that familiar with useContext(), so I can't say if you're using it correctly.
Login.js:
import { useContext, useEffect } from 'react';
import { makeStyles } from '#material-ui/core';
import Container from '#material-ui/core/Container';
import LoginForm from '../components/login/LoginForm';
import AuthContext from '../store/auth-context';
const useStyles = makeStyles(theme => ({
pageWrapper: {
height: '100vh',
display: 'flex',
flexDirection: 'column',
backgroundColor: theme.palette.background.default,
},
pageContainer: {
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
flexGrow: '1',
},
}));
function httpReducer(state, action) {
switch (action.type) {
case 'SEND':
return {
data: null,
error: null,
status: 'pending',
};
case 'SUCCESS':
return {
data: action.responseData,
error: null,
status: 'completed',
};
case 'ERROR':
return {
data: null,
error: action.errorMessage,
status: 'completed',
};
default:
return state;
}
}
function Login() {
const [httpState, dispatch] = useReducer(httpReducer, {
status: startWithPending ? 'pending' : null,
data: null,
error: null,
});
const sendRequest = async requestData => {
dispatch({ type: 'SEND' });
try {
let config = {
method: 'post',
url: `${BACKEND_URL}/api/auth/`,
headers: { 'Content-Type': 'application/json' },
data: {
email: requestData.email,
password: requestData.password,
},
};
const response = await axios(config);
dispatch({ type: 'SUCCESS', responseData: response.data });
} catch (error) {
dispatch({
type: 'ERROR',
errorMessage: error.response.data.message || 'Something went wrong!',
});
}
};
const authCtx = useContext(AuthContext);
const loginHandler = (email, password) => {
sendRequest({ email, password });
};
useEffect(() => {
if (httpState.status === 'pending') {
console.log('making request');
}
}, [httpState.status]);
useEffect(() => {
if (httpState.status === 'completed' && httpState.data) {
console.log('updateContext');
authCtx.login(httpState.data);
}
}, [httpState.status, httpState.data]);
useEffect(() => {
if (httpState.status === 'completed' && httpState.error) {
console.log(httpState.error);
}
}, [httpState.status, httpState.error]);
const classes = useStyles();
return (
<div className={classes.pageWrapper}>
<Container maxWidth="md" className={classes.pageContainer}>
<LoginForm status={httpState.status} onLoginHandler={loginHandler} />
</Container>
</div>
);
}
export default Login;
AuthContext.js:
import React, { useState } from 'react';
import { useEffect } from 'react';
import {
getUser,
removeUser,
saveUser,
getExpirationTime,
clearExpirationTime,
setExpirationTime,
} from '../utils/local-storage';
const AuthContext = React.createContext({
token: '',
isLoggedIn: false,
login: () => {},
logout: () => {},
});
const calculateRemainingTime = expirationTime => {
const currentTime = new Date().getTime();
const adjExpirationTime = new Date(expirationTime).getTime();
const remainingDuration = adjExpirationTime - currentTime;
return remainingDuration;
};
// is this asynchronous?
const retrieveStoredToken = () => {
const storedToken = getUser();
const storedExpirationDate = getExpirationTime();
const remainingTime = calculateRemainingTime(storedExpirationDate);
if (remainingTime <= 60) {
removeUser();
clearExpirationTime();
return null;
}
return {
token: storedToken,
duration: remainingTime,
};
};
export const AuthContextProvider = ({ children }) => {
const [tokenData, setTokenData] = useState(null);
const [logoutTimer, setLogoutTimer] = useState(null);
useEffect(() => {
const tokenData_ = retrieveStoredToken(); //is this asynchronous?
if (tokenData_) {
setTokenData(tokenData_);
}
}, []);
const userIsLoggedIn = !!(tokenData && tokenData.token);
const logoutHandler = () => {
setTokenData(null);
removeUser();//is this asynchronous?
clearExpirationTime();
if (logoutTimer) {
clearTimeout(logoutTimer);
//clear logoutTimer state here? -> setLogoutTimer(null);
}
};
const loginHandler = ({ token, user }) => {
console.log('login Handler runs');
console.log(token, user.expiresIn);
setTokenData({ token });
saveUser(token);
setExpirationTime(user.expiresIn);
const remainingTime = calculateRemainingTime(user.expiresIn);
setLogoutTimer(setTimeout(logoutHandler, remainingTime));
};
useEffect(() => {
if (tokenData && tokenData.duration) {
console.log(tokenData.duration);
setLogoutTimer(setTimeout(logoutHandler, tokenData.duration));
}
}, [tokenData]);
const user = {
token: tokenData.token,
isLoggedIn: userIsLoggedIn,
login: loginHandler,
logout: logoutHandler,
};
return <AuthContext.Provider value={user}>{children}</AuthContext.Provider>;
};
export default AuthContext;

Related

console error :Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'data') at handleClick

In this page the user can login, but if the untilDate is bigger than the current date it should log out the user. The code runs fine 1/2 times, the other giving me the error on the title.
I am working with createContext for user login. This is the AuthContext file
import React from "react";
import { createContext, useEffect, useReducer } from "react";
const INITIAL_STATE = {
user: JSON.parse(localStorage.getItem("user")) || null,
loading: false,
error: null,
};
export const AuthContext = createContext(INITIAL_STATE);
const AuthReducer = (state, action) => {
switch (action.type) {
case "LOGIN_START":
return {
user: null,
loading: true,
error: null,
};
case "LOGIN_SUCCESS":
return {
user: action.payload,
loading: false,
error: null,
};
case "LOGOUT":
return {
user: null,
loading: false,
error: null,
};
case "LOGIN_FAILURE":
return {
user: null,
loading: false,
error: action.payload,
};
case "UPDATE_USER_DATE":
const updatedUser = { ...state.user };
updatedUser.activeUntil = action.payload;
return {
...state,
user: updatedUser,
};
default:
return state;
}
};
export const AuthContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(AuthReducer, INITIAL_STATE);
useEffect(() => {
localStorage.setItem("user", JSON.stringify(state.user));
}, [state.user]);
return (
<AuthContext.Provider
value={{
user: state.user,
loading: state.loading,
error: state.error,
dispatch,
}}
>
{children}
</AuthContext.Provider>
);
};
When the user clicks the login button, it runs the handleClick function:
const handleClick = async (e) => {
e.preventDefault();
dispatch({ type: "LOGIN_START" });
let date = new Date().toJSON();
let userdate = date;
try {
const res = await axios.post("/auth/signin", credentials);
dispatch({ type: "LOGIN_SUCCESS", payload: res.data.details });
userdate = user.activeUntil;
//do if date is <=current datem dispatch logout
} catch (err) {
if (userdate > date) {
console.log("undefined data");
} else {
dispatch({ type: "LOGIN_FAILURE", payload: err.response.data });
}
}
if (userdate > date) {
dispatch({ type: "LOGOUT" });
console.log("If you are seeing this your contract has expired");
} else {
// navigate("/myinfo");
}
};
The console error happens from this line dispatch({ type: "LOGIN_FAILURE", payload: err.response.data });
Is there a way I can bypass this error or a different way I can write my code to make it work?
This is the full code of login page
import React from "react";
import axios from "axios";
import { useContext, useState } from "react";
import { useNavigate } from "react-router-dom";
import { AuthContext } from "../../context/AuthContext";
import {
Container,
FormWrap,
FormContent,
Form,
FormInput,
FormButton,
Icon,
FormH1,
SpanText,
IconWrapper,
IconL,
} from "./signinElements";
import Image from "../../images/Cover.png";
const Login = () => {
const [credentials, setCredentials] = useState({
namekey: undefined,
password: undefined,
});
/* */
// to view current user in console
const { user, loading, error, dispatch } = useContext(AuthContext);
let msg;
const navigate = useNavigate();
const handleChange = (e) => {
setCredentials((prev) => ({ ...prev, [e.target.id]: e.target.value }));
};
const handleClick = async (e) => {
e.preventDefault();
dispatch({ type: "LOGIN_START" });
let date = new Date().toJSON();
let userdate = date;
try {
const res = await axios.post("/auth/signin", credentials);
dispatch({ type: "LOGIN_SUCCESS", payload: res.data.details });
userdate = user.activeUntil;
//do if date is <=current datem dispatch logout
} catch (err) {
if (userdate > date) {
console.log("undefined data");
} else {
dispatch({ type: "LOGIN_FAILURE", payload: err.response.data });
}
}
if (userdate > date) {
dispatch({ type: "LOGOUT" });
console.log("If you are seeing this your contract has expired");
} else {
// navigate("/myinfo");
}
};
// console.log(user.activeUntil); //type to view current user in console
return (
<>
<Container>
<IconWrapper>
<IconL to="/">
<Icon src={Image}></Icon>
</IconL>
</IconWrapper>
<FormWrap>
<FormContent>
<Form action="#">
<FormH1>
Sign in with the namekey and password written to you on your
contract.
</FormH1>
<FormInput
type="namekey"
placeholder="Namekey"
id="namekey"
onChange={handleChange}
required
/>
<FormInput
type="password"
placeholder="Password"
id="password"
onChange={handleChange}
/>
<FormButton disabled={loading} onClick={handleClick}>
Login
</FormButton>
<SpanText>{msg}</SpanText>
{error && <SpanText>{error.message}</SpanText>}
{error && (
<SpanText>
Forgot namekey or password? Contact our support team +355 69
321 5237
</SpanText>
)}
</Form>
</FormContent>
</FormWrap>
</Container>
</>
);
};
export default Login;
The problem was i was trying to call a localy stored user and 1 time it wasnt loaded and the other it was. Simply fixed it by changing the if statement to check directly in result details without having to look in local storage.
const [expired, setExpired] = useState(false);
const handleClick = async (e) => {
e.preventDefault();
dispatch({ type: "LOGIN_START" });
try {
const res = await axios.post("/auth/signin", credentials);
dispatch({ type: "LOGIN_SUCCESS", payload: res.data.details });
let date = new Date().toJSON();
if (res.data.details.activeUntil < date) {
dispatch({ type: "LOGOUT" });
console.log("Users contract has expired");
setExpired(!expired);
} else {
navigate("/myinfo");
}
} catch (err) {
dispatch({ type: "LOGIN_FAILURE", payload: err.response.data });
}
};

How can I make nextjs router.isReady to true when rendering a component in Jest?

I am writing a Jest/Testing Library unit test.
In test, I wrap my component in AuthProvider component:
const handlers: Record<string, (state: State, action: Action) => State> = {
INITIALIZE: (state: State, action: InitializeAction): State => {
const { isAuthenticated, permissions, user } = action.payload;
return {
...state,
isAuthenticated,
isInitialized: true,
permissions,
user,
};
},
LOGIN: (state: State): State => {
return {
...state,
isAuthenticated: true,
};
},
LOGOUT: (state: State): State => ({
...state,
isAuthenticated: false,
permissions: [],
}),
};
const reducer = (state: State, action: Action): State =>
handlers[action.type] ? handlers[action.type](state, action) : state;
const AuthContext = createContext<AuthContextValue>({
...initialState,
platform: 'JWT',
login: () => Promise.resolve(),
logout: () => Promise.resolve(),
});
export const AuthProvider: FC<AuthProviderProps> = (props) => {
const { children } = props;
const [state, dispatch] = useReducer(reducer, initialState);
const router = useRouter();
const reduxDispatch = useDispatch();
useEffect(() => {
const initialize = async (): Promise<void> => {
try {
if (router.isReady) {
const { token, permissions, user, companyId } = router.query;
// TODO: Move all of this stuff from query and localstorage into session
const accessToken =
(token as string) || window.localStorage.getItem('accessToken');
const permsStorage = window.localStorage.getItem('perms');
const perms = (permissions as string) || permsStorage;
const userStorage = window.localStorage.getItem('user');
const selectedCompanyId =
(companyId as string) || window.localStorage.getItem('companyId');
const authUser = (user as string) || userStorage;
if (accessToken && perms) {
setSession(accessToken, perms, authUser);
try {
// check if user is admin by this perm, probably want to add a flag later
if (perms.includes('create:calcs')) {
if (!selectedCompanyId) {
const response = await reduxDispatch(getAllCompanies());
const companyId = response.payload[0].id;
reduxDispatch(companyActions.selectCompany(companyId));
reduxDispatch(getCurrentCompany({ companyId }));
} else {
reduxDispatch(
companyActions.selectCompany(selectedCompanyId),
);
await reduxDispatch(
getCurrentCompany({ companyId: selectedCompanyId }),
);
}
} else {
reduxDispatch(companyActions.selectCompany(selectedCompanyId));
await reduxDispatch(
getCurrentCompany({ companyId: selectedCompanyId }),
);
}
} catch (e) {
console.warn(e);
} finally {
dispatch({
type: 'INITIALIZE',
payload: {
isAuthenticated: true,
permissions: JSON.parse(perms),
user: JSON.parse(authUser),
},
});
}
if (token || permissions) {
router.replace(router.pathname, undefined, { shallow: true });
}
} else {
dispatch({
type: 'INITIALIZE',
payload: {
isAuthenticated: false,
permissions: [],
user: undefined,
},
});
setSession(undefined);
if (router.pathname !== '/client-landing') {
router.push('/login');
}
}
}
} catch (err) {
console.error(err);
dispatch({
type: 'INITIALIZE',
payload: {
isAuthenticated: false,
permissions: [],
user: undefined,
},
});
//router.push('/login');
}
};
initialize();
}, [router.isReady]);
const login = useCallback(async (): Promise<void> => {
const response = await axios.get('/auth/sign-in-with-intuit');
window.location = response.data;
}, []);
const logout = useCallback(async (): Promise<void> => {
const token = localStorage.getItem('accessToken');
// only logout if already logged in
if (token) {
dispatch({ type: 'LOGOUT' });
}
setSession(null);
router.push('/login');
}, [dispatch, router]);
return (
<AuthContext.Provider
value={{
...state,
platform: 'JWT',
login,
logout,
}}
>
{state.isInitialized && children}
</AuthContext.Provider>
);
};
AuthProvider.propTypes = {
children: PropTypes.node.isRequired,
};
export default AuthContext;
When I render the component wrapped with AuthProvider, it says
TypeError: Cannot read property 'isReady' of null
217 |
218 | initialize();
> 219 | }, [router.isReady]);
How can I make the router exist?
This is how I am rendering in Jest:
render(
<HelmetProvider>
<Provider store={mockStore(initState)}>
<AuthProvider>
<BenchmarksPage />
</AuthProvider>
,
</Provider>
</HelmetProvider>,
);
Note that I do not have to check if router works. I just have to make it run so that I can unit test the UI, no implementation details.

disable default Scroll to top in web application

I'm new to React and Web.
I am trying to load some chats data, whenever I add some chats to the top of the chat list, automatically chats container scrolled to the top of chats, I mean first chat in term of creating time.
how to disable this scrolling behavior?
I also tried a library called reverse-infinite-search.
useChatLoad.ts
import {useEffect, useState} from "react";
import axios, {Canceler} from "axios";
import {API_KEY, BASE_SANGRIA_URL} from "../apis/BaseApi";
import {Message} from "../models/Message";
export default function useChat(visitorId: string, fetchBeforeTimestampMillis: number, scrollToBottom: () => void) {
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<boolean>(false);
const [chats, setChats] = useState<Message[]>([]);
const [hasMore, setHasMore] = useState<boolean>(false);
useEffect(() => {
setChats([]);
}, [visitorId]);
const onNewMessageReceived = (m: Message) => {
setChats([...chats, m]);
}
useEffect(() => {
setLoading(true);
setError(false);
let canceler: Canceler;
axios({
method: "POST",
url: BASE_URL,
data: {userId: visitorId, fetchBeforeTimestampMillis: fetchBeforeTimestampMillis},
headers: {'Content-Type': 'application/json', "API-KEY": API_KEY},
cancelToken: new axios.CancelToken(c => canceler = c)
}).then(res => {
console.log("fetch called")
if (res.status != 200 || res.data.error != null) {
console.log(res.status + " " + res.data.error);
setError(true);
return;
}
let messages: Message[] = res.data.messages;
messages = messages.reverse();
if (chats.length == 0 && messages.length != 0)
scrollToBottom()
setChats(prevChats => {
return [...messages, ...prevChats]
})
setHasMore(res.data.messages.length > 0);
setLoading(false);
}).catch(e => {
if (axios.isCancel(e)) return;
console.log("l41 useChatLoad ", e);
setError(true);
})
}, [visitorId, fetchBeforeTimestampMillis])
return {loading, error, chats, hasMore, onNewMessageReceived};
}
ChatContent.tsx
import React, {createRef, useCallback, useEffect, useRef, useState} from "react";
import styles from './ChatContent.module.css';
import ChatItem from "../chat-item/ChatItem";
import {Message} from "../../models/Message";
import InputField from "../input-field/InputField";
import useChatsLoad from "../../custom-hooks/useChasLoad";
import InfiniteScrollReverse from "../inf-scroll/InfiniteScrollReverse";
import {OtherOperatorMessagePayload, Sangria, VisitorMessagePayload} from "../../sangria/Sangria";
import {isEmptyText} from "../../tools/Tools";
interface Props {
isOnline: boolean
visitorId: string,
onOperatorMessageReceived: (m: OtherOperatorMessagePayload) => void
onCustomerMessageReceived: (m: VisitorMessagePayload) => void
}
const ChatContent: React.FC<Props> = (props: Props) => {
const [msg, setMsg] = useState<string>("");
const [fetchBeforeTimeStamp, setFetchBeforeTimeStamp] = useState<number>(Date.now());
const [sangria, setSangria] = useState<Sangria>();
const messagesEndRef = useRef<HTMLDivElement>(null);
function scrollToBottom() {
console.log("scroll to bottom called")
messagesEndRef.current?.scrollIntoView({behavior: "auto"})
}
const {
chats,
hasMore,
loading,
error,
onNewMessageReceived
} = useChatsLoad(props.visitorId, fetchBeforeTimeStamp, scrollToBottom);
useEffect(() => {
let sg = new Sangria();
sg.setReceiveMessageFromOtherOperatorCallback(data => {
props.onOperatorMessageReceived(data);
if (data.message.customerId != props.visitorId) return;
let newMessage: Message = {
meta: data.message.meta,
messageType: data.message.messageType,
body: data.message.body,
id: data.message.id,
createdAt: data.message.createdAt,
sender: data.sender
}
onNewMessageReceived(newMessage);
});
sg.setVisitorTypingCallback(d => {
})
sg.setReceiveMessageFromVisitorCallback(data => {
props.onCustomerMessageReceived(data);
if (data.customerId != props.visitorId) return;
let newMessage: Message = {
sender: data.sender,
createdAt: data.createdAt,
id: data.id,
body: data.body,
messageType: data.messageType,
meta: data.meta,
}
onNewMessageReceived(newMessage);
})
setSangria(sg);
}, [])
// const observer = useRef<IntersectionObserver>();
//
// const firstChatItemElement = useCallback(node => {
// if (loading) return;
//
// if (observer.current) observer.current.disconnect();
//
// observer.current = new IntersectionObserver(entries => {
// if (entries[0].isIntersecting && hasMore) {
// updateFetchBeforeTimeStamp();
// }
// })
// if (node) observer.current?.observe(node);
// }, [loading, hasMore])
//
function sendMessage() {
if (isEmptyText(props.visitorId)) {
setMsg("");
return;
}
sangria?.sendMessage("text", msg, "", props.visitorId);
setMsg("")
}
function sendOperatorTypingEvent() {
if (isEmptyText(props.visitorId)) {
return;
}
sangria?.sentOperatorTypingEvent(props.visitorId);
}
function sendImage() {
}
useEffect(() => {
updateFetchBeforeTimeStamp();
},[chats.length])
function updateFetchBeforeTimeStamp() {
console.log("fetch beforeTimeStamp called")
if (chats.length == 0)
setFetchBeforeTimeStamp(Date.now());
else
setFetchBeforeTimeStamp(chats[0].createdAt);
}
return (
<div className={styles.main__chatcontent}>
<div className={styles.content__header}>
</div>
<div className={styles.content__body}>
<InfiniteScrollReverse className={styles.chat_items} loadMore={() => {
updateFetchBeforeTimeStamp()
}} hasMore={hasMore} isLoading={loading} loadArea={30}>
{chats.map((itm, index) => {
return (<ChatItem key={itm.id} message={itm} ref={index == 0 ? null : null}/>)
})}
<div key="end" ref={messagesEndRef}/>
</InfiniteScrollReverse>
{/*<div className={styles.chat_items}>*/}
{/* */}
{/*</div>*/}
</div>
<InputField onAttach={sendImage} onSend={sendMessage} onTextChanged={e => {
setMsg(e.target.value);
sendOperatorTypingEvent()
}} text={msg}/>
</div>
)
}
export default ChatContent;
InfiniteScrollReverse.js
import React, { useEffect, useRef, useState } from "react";
import PropTypes from "prop-types";
function InfiniteScrollReverse({ className, isLoading, hasMore, loadArea, loadMore, children }) {
const infiniteRef = useRef();
const [currentPage, setCurrentPage] = useState(1);
const [scrollPosition, setScrollPosition] = useState(0);
// Reset default page, if children equals to 0
useEffect(() => {
if (children.length === 0) {
setCurrentPage(1);
}
}, [children.length]);
useEffect(() => {
console.log("useEffect in inf -scroll called")
let { current: scrollContainer } = infiniteRef;
function onScroll() {
// Handle scroll direction
console.log(scrollContainer.scrollTop," $$$")
if (scrollContainer.scrollTop > scrollPosition) {
// Scroll bottom
} else {
// Check load more scroll area
if (scrollContainer.scrollTop <= loadArea && !isLoading) {
// Check for available data
if (hasMore) {
// Run data fetching
const nextPage = currentPage + 1;
setCurrentPage(nextPage);
loadMore(nextPage);
}
}
}
// Save event scroll position
setScrollPosition(scrollContainer.scrollTop);
}
scrollContainer.addEventListener("scroll", onScroll);
return () => {
scrollContainer.removeEventListener("scroll", onScroll);
};
}, [currentPage, hasMore, isLoading, loadArea, loadMore, scrollPosition]);
useEffect(() => {
let { current: scrollContainer } = infiniteRef;
if (children.length) {
// Get available top scroll
const availableScroll = scrollContainer.scrollHeight - scrollContainer.clientHeight;
// Get motion for first page
if (currentPage === 1) {
// Move data to bottom for getting load more area
if (availableScroll >= 0) {
scrollContainer.scrollTop = availableScroll;
}
} else {
// Add scroll area for other pages
if (hasMore) {
scrollContainer.scrollTop = scrollContainer.clientHeight;
}
}
}
}, [children.length, currentPage, hasMore]);
return (
<div className={className} ref={infiniteRef}>
{children}
</div>
);
}
InfiniteScrollReverse.propTypes = {
className: PropTypes.string.isRequired,
children: PropTypes.array,
hasMore: PropTypes.bool.isRequired,
isLoading: PropTypes.bool.isRequired,
loadMore: PropTypes.func.isRequired,
loadArea: PropTypes.number,
};
InfiniteScrollReverse.defaultProps = {
className: "InfiniteScrollReverse",
children: [],
loadArea: 30,
};
export default InfiniteScrollReverse;

react js Axios request failed: TypeError: Cannot read property 'token' of undefined?

i have get token from login with react redux, if i am try to authorized it with this token. the error is show Axios request failed: TypeError: Cannot read property 'token' of undefined i want to authorized it with token. the token is stored in localstorage but it can't authorized it when i am using (Token ${props.token} if i am trying this way (Token 5302f4340a76cd80a855286c6d9e0e48d2f519cb} then my AritcleList.js is Authorized it
here is the react-redux authentication
authAction.js
import axios from 'axios';
import * as actionTypes from './actionTypes';
export const authStart = () => {
return {
type: actionTypes.AUTH_START
}
}
export const authSuccess = token => {
return {
type: actionTypes.AUTH_SUCCESS,
token: token
}
}
export const authFail = error => {
return {
type: actionTypes.AUTH_FAIL,
error: error
}
}
export const logout = () => {
localStorage.removeItem('token');
return {
type: actionTypes.AUTH_LOGOUT
};
}
export const authLogin = (userData) => {
return dispatch => {
dispatch(authStart());
axios.post('http://localhost:8000/rest-auth/login/', userData)
.then(res => {
const token = res.data.key;
localStorage.setItem('token', token);
dispatch(authSuccess(token));
})
.catch(err => {
dispatch(authFail(err))
})
}
}
authReducer.js
import * as actionTypes from '../actions/actionTypes';
import { updateObject } from '../utility';
const initialState = {
isAuthenticated: null,
token: null,
error: null,
loading: false
}
const authStart = (state, action) => {
return updateObject(state, {
isAuthenticated: false,
error: null,
loading: true
});
}
const authSuccess = (state, action) => {
return updateObject(state, {
isAuthenticated: true,
token: action.token,
error: null,
loading: false
});
}
const authFail = (state, action) => {
return updateObject(state, {
error: action.error,
loading: false
});
}
const authLogout = (state, action) => {
return updateObject(state, {
token: null
});
}
export default function (state = initialState, action) {
switch (action.type) {
case actionTypes.AUTH_START: return authStart(state, action);
case actionTypes.AUTH_SUCCESS: return authSuccess(state, action);
case actionTypes.AUTH_FAIL: return authFail(state, action);
case actionTypes.AUTH_LOGOUT: return authLogout(state, action);
default:
return state;
}
}
articleList.js
import React, { useState, useEffect } from 'react';
import { Container, Row, Col } from 'react-bootstrap';
import Card from '../components/Card'
import FullPageLoader from "../components/FullPageLoader";
import axios from 'axios';
import { connect } from 'react-redux'
const NewsList = () => {
const [items, setItems] = useState([])
const [isLoading, setLoading] = useState(true)
const [isAuthenticated, setAuth] = useState(true); //i don't know how to authenticate it when i also login
useEffect((props) => {
const fetchItems = async () => {
try {
const config = {
headers: {
'Content-Type': 'application/json',
Authorization: `Token ${props.token}`
}
}
const res = await axios.get(`${process.env.REACT_APP_API_URL}/api/`, config);
setItems(res.data)
setLoading(false);
}
catch (err) {
console.log(`😱 Axios request failed: ${err}`);
}
}
fetchItems()
})
}, [items]);
return (
<Container className="mt-5">
< div className="bread-header" >
<h5>Dashboard</h5>
</div >
<hr />
<Row>
<Col sm={8}>
{
isLoading ? <FullPageLoader /> :
<div>
{itemData.map((item, index) => (
<Card key={index} item={item} isAuthenticated={isAuthenticated} ></Card>
))}
</div>
}
</Col>
</Row>
</Container >
)
}
const mapStateToProps = (state) => {
return {
isAuthenticated: state.auth.token,
}
}
export default connect(mapStateToProps)(NewsList)
useEffect doesn't take any arguments, so props will always be undefined here:
useEffect((props) => {
I would guess you want to do:
const NewsList = (props) => {
// ...
useEffect(() => {
// ...
}, [items]);
// ...
}
const mapStateToProps = (state) => {
return {
isAuthenticated: !!state.auth.token,
token: state.auth.token
}
}
export default connect(mapStateToProps)(NewsList)

Apollo Queries triggered and causing rerendering in useContext on URL Change

GIF of Rerender occuring
I'm not sure how to proceed. As you can see, the Header's state (as passed down via context) is switching from the user's data --> undefined --> same user's data. This occurs every time there's a url change, and doesn't happen when I do things that don't change the url (like opening the cart for example).
Is this expected behaviour? Is there any way I can get the query in my context to only be called when there is no user data or when the user data changes? I tried using useMemo, but to no avail.
auth.context
import React, { useState} from "react";
import {
CURRENT_USER,
GET_LOGGED_IN_CUSTOMER,
} from "graphql/query/customer.query";
import { gql, useQuery, useLazyQuery } from "#apollo/client";
import { isBrowser } from "components/helpers/isBrowser";
export const AuthContext = React.createContext({});
export const AuthProvider = ({ children }) => {
const [customer, { data, loading, error }] = useLazyQuery(
GET_LOGGED_IN_CUSTOMER,
{
ssr: true,
}
);
const { data: auth } = useQuery(CURRENT_USER, {
onCompleted: (auth) => {
console.log(auth);
customer({
variables: {
where: {
id: auth.currentUser.id,
},
},
});
},
ssr: true,
});
console.log(data);
const isValidToken = () => {
if (isBrowser && data) {
const token = localStorage.getItem("token");
if (error) {
console.log("error", error);
}
if (token && data) {
console.log("token + auth");
return true;
} else return false;
}
};
const [isAuthenticated, makeAuthenticated] = useState(isValidToken());
function authenticate() {
makeAuthenticated(isValidToken());
}
function signout() {
makeAuthenticated(false);
localStorage.removeItem("token");
}
return (
<AuthContext.Provider
value={{
isAuthenticated,
data,
authenticate,
auth,
signout,
}}
>
{children}
</AuthContext.Provider>
);
};
(In Header, userData is equal to data just passed through an intermediary component (to provide to mobile version)).
header.tsx
import React, { useContext } from "react";
import Router, { useRouter } from "next/router";
import { useApolloClient } from "#apollo/client";
import { openModal } from "#redq/reuse-modal";
import SearchBox from "components/SearchBox/SearchBox";
import { SearchContext } from "contexts/search/search.context";
import { AuthContext } from "contexts/auth/auth.context";
import LoginModal from "containers/LoginModal";
import { RightMenu } from "./Menu/RightMenu/RightMenu";
import { LeftMenu } from "./Menu/LeftMenu/LeftMenu";
import HeaderWrapper from "./Header.style";
import LogoImage from "image/hatchli-reduced-logo.svg";
import { isCategoryPage } from "../is-home-page";
type Props = {
className?: string;
token?: string;
pathname?: string;
userData?: any;
};
const Header: React.FC<Props> = ({ className, userData }) => {
const client = useApolloClient();
const { isAuthenticated, signout } = useContext<any>(AuthContext);
const { state, dispatch } = useContext(SearchContext);
console.log(isAuthenticated);
console.log(userData);
const { pathname, query } = useRouter();
const handleLogout = () => {
if (typeof window !== "undefined") {
signout();
client.resetStore();
Router.push("/medicine");
}
};
const handleJoin = () => {
openModal({
config: {
className: "login-modal",
disableDragging: true,
width: "auto",
height: "auto",
animationFrom: { transform: "translateY(100px)" },
animationTo: { transform: "translateY(0)" },
transition: {
mass: 1,
tension: 180,
friction: 26,
},
},
component: LoginModal,
componentProps: {},
closeComponent: "",
closeOnClickOutside: true,
});
};
const onSearch = (text: any) => {
dispatch({
type: "UPDATE",
payload: {
...state,
text,
},
});
};
const { text } = state;
const onClickHandler = () => {
const updatedQuery = query.category
? { text: text, category: query.category }
: { text };
Router.push({
pathname: pathname,
query: updatedQuery,
});
};
const showSearch = isCategoryPage(pathname);
return (
<HeaderWrapper className={className}>
<LeftMenu logo={LogoImage} />
{showSearch && (
<SearchBox
className="headerSearch"
handleSearch={(value: any) => onSearch(value)}
onClick={onClickHandler}
placeholder="Search anything..."
hideType={true}
minimal={true}
showSvg={true}
style={{ width: "100%" }}
value={text || ""}
/>
)}
<RightMenu
isAuth={userData}
onJoin={handleJoin}
onLogout={handleLogout}
avatar={userData && userData.user && userData.user.avatar}
/>
</HeaderWrapper>
);
};
export default Header;

Categories