Apollo Queries triggered and causing rerendering in useContext on URL Change - javascript

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;

Related

React Context API state update leads to infinite loop

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;

Got an Undefined reducer error in React Native project with Redux

I am trying to use redux in my app for the first time and i set up whole boilerplate for it but i got an error which says Error: The slice reducer for key "AuthReducer" returned undefined during initialization. as it says i checked the state value passed in reducer but i can't figure it out, Here i am adding my code sample.
reducer.js
import {combineReducers} from 'redux'
import { SIGN_IN, SIGN_OUT, SIGN_UP, MOVIE_ADDED, MOVIE_REMOVED } from './ActionTypes'
const initialMovieState = {
savedMovies: [
{
id: '',
name: ''
}
]
}
const initialAuthState = {
userEmail: '',
userPassword: '',
userToken: '',
}
export const AuthReducer = (state=initialAuthState, action) => {
switch (action.type) {
case SIGN_IN:
return {
...state,
userToken: action.payload.token
}
case SIGN_UP:
return {
...state,
userEmail: action.payload.email,
userPassword: action.payload.password
}
case SIGN_OUT:
return {
...state,
userToken: ''
}
default:
state
}
}
export const MovieReducer = (state=initialMovieState, action) => {
switch (action.type) {
case MOVIE_ADDED:
return {
...state,
savedMovies: state.savedMovies.concat({
id: action.payload.movieId,
name: action.movieName
})
}
case MOVIE_REMOVED:
return state.filter(movie => movie.id !== action.payload.movieId)
default:
state
}
}
const RootReducer = combineReducers({
AuthReducer,
MovieReducer
})
export default RootReducer
actions.js
import {SIGN_IN, SIGN_OUT, SIGN_UP, MOVIE_ADDED, MOVIE_REMOVED} from './ActionTypes'
export const sign_in = (user) => (
{
type: SIGN_IN,
payload: {
token: user
}
}
)
export const sign_up = (user) => (
{
type: SIGN_UP,
payload: {
email: user.email,
password: user.password
}
}
)
export const sign_out = () => (
{
type: SIGN_OUT,
}
)
export const movie_added = (movie) => (
{
type: MOVIE_ADDED,
payload: {
movieId: movie.id,
movieName: movie.name,
}
}
)
export const movie_removed = () => (
{
type: MOVIE_REMOVED
}
)
store.js
import { createStore } from 'redux'
import {composeWithDevTools} from 'redux-devtools-extension'
import rootReducer from './Reducer'
const Store = createStore(rootReducer, composeWithDevTools())
export default Store
I've wrapped the whole app in Provider with store as an argument in App.js
SignUpScreen.js
import {useDispatch, useStore} from 'react-redux'
import {sign_up} from '../redux/Actions'
const SignUpScreen = () => {
const navigation = useNavigation()
const dispatch = useDispatch()
const Store = useStore()
...
const handleSubmit = () => {
if(isValidEmail === true && isValidPass === true && isPassMatched === true){
console.log(Store.getState())
dispatch(sign_up({email: email, password: password}))
console.log(Store.getState())
navigation.navigate('signin')
ToastAndroid.showWithGravity(
'Account created.',
ToastAndroid.LONG,
ToastAndroid.BOTTOM
)
} else {
ToastAndroid.showWithGravity(
'Invalid Email or Password',
ToastAndroid.LONG,
ToastAndroid.BOTTOM
)
}
}
...
return(
{/* register button */}
<TouchableOpacity style={styles.regBtnCont} onPress={() => handleSubmit()}>
<Text style={styles.regBtnText}>Register</Text>
</TouchableOpacity>
)
}
Any help will be appriciated, Thank you.

State getting reinitialized to its original value - useState or useReduce

I created a custom hook (useAuth) to extend the third-party Authentication service Auth0's useAuth0 hook and set some local variables that holds basic user information, such as userId.
I have a master account that can impersonate other accounts. This means that it overrides the userId from my custom hook and it gets propagated throughout the system.
The problem that I'm facing is that whenever I call the impersonate function that changes this hook's inner state, it changes it, but then reinitializes itself. I don't know what is causing this reinitialization. The code is down below.
import { useAuth0 } from '#auth0/auth0-react';
import produce from 'immer';
import { useState, useEffect, useCallback, useReducer, Reducer } from 'react';
import { AccountType, Auth0HookUser, TenantInfo, TenantType } from '../#dts';
type AuthVariants =
| 'INDIVIDUAL_TEACHER'
| 'INSTITUTION_TEACHER'
| 'STUDENT'
| 'SECRETARY'
| 'COORDINATOR'
| 'ADMINISTRATOR';
type AuthTenant = {
accountType: AccountType;
tenantType: TenantType;
employeeId: string;
tenantId: string;
selectedTenant: TenantInfo;
variant: AuthVariants;
mode: 'IMPERSONATION' | 'NORMAL';
user: Auth0HookUser;
};
const defaultAuthTenant: () => AuthTenant = () => ({
accountType: 'teacher',
employeeId: '',
mode: 'NORMAL',
selectedTenant: {
accountType: 'teacher',
tenantType: 'INSTITUTION',
tenantId: '',
},
tenantId: '',
tenantType: 'INSTITUTION',
variant: 'INDIVIDUAL_TEACHER',
user: {
name: '',
nickname: '',
} as any,
});
type Action =
| {
type: 'UPDATE_AUTH';
auth: AuthTenant;
}
| {
type: 'IMPERSONATE';
impersonatedEmployeeId: string;
impersonatedName: string;
accountType: AccountType;
}
| {
type: 'EXIT_IMPERSONATION';
};
type State = {
current: AuthTenant;
original: AuthTenant;
};
const reducer = produce((state: State, action: Action) => {
switch (action.type) {
case 'IMPERSONATE':
console.log('Impersonating');
const selectedTenant =
state.current.user['https://app.schon.io/user_data'].tenants[0];
state.current = {
...state.current,
user: {
...state.current.user,
name: action.impersonatedName,
nickname: action.impersonatedName,
'https://app.schon.io/user_data': {
...state.current.user['https://app.schon.io/user_data'],
userId: action.impersonatedEmployeeId,
},
},
mode: 'IMPERSONATION',
accountType: action.accountType,
employeeId: action.impersonatedEmployeeId,
variant: getVariant(action.accountType, selectedTenant.tenantType),
selectedTenant: {
...state.current.selectedTenant,
accountType: action.accountType,
},
};
return state;
case 'UPDATE_AUTH':
state.current = action.auth;
state.original = action.auth;
return state;
default:
return state;
}
});
export function useAuth() {
const { user: _user, isAuthenticated, isLoading, ...auth } = useAuth0();
const user = _user as Auth0HookUser;
const [selectedTenantIndex, setSelectedTenantIndex] = useState(0);
const [state, dispatch] = useReducer<Reducer<State, Action>>(reducer, {
current: defaultAuthTenant(),
original: defaultAuthTenant(),
});
const impersonate = (
impersonatedEmployeeId: string,
accountType: AccountType,
impersonatedName: string,
) => {
if (!user) {
return;
}
dispatch({
type: 'IMPERSONATE',
accountType,
impersonatedEmployeeId,
impersonatedName,
});
};
const exitImpersonation = useCallback(() => {
dispatch({ type: 'EXIT_IMPERSONATION' });
}, []);
useEffect(() => {
if (isLoading || (!isLoading && !isAuthenticated)) {
return;
}
if (!user || state.current.mode === 'IMPERSONATION') {
return;
}
console.log('Use Effect Running');
const { tenants, userId } = user['https://app.schon.io/user_data'];
const selectedTenant = tenants[selectedTenantIndex];
const { accountType, tenantType } = selectedTenant;
dispatch({
type: 'UPDATE_AUTH',
auth: {
tenantId: selectedTenant.tenantId,
employeeId: userId,
mode: 'NORMAL',
variant: getVariant(accountType, tenantType),
user,
selectedTenant,
accountType,
tenantType,
},
});
}, [
user,
isAuthenticated,
isLoading,
selectedTenantIndex,
state.current.mode,
]);
console.log('State Current', state.current);
return {
isAuthenticated,
isLoading,
impersonate,
exitImpersonation,
setSelectedTenantIndex,
...auth,
...state.current,
};
}
function getVariant(
accountType: AccountType,
tenantType: TenantType,
): AuthVariants {
if (accountType === 'teacher') {
return tenantType === 'INSTITUTION'
? 'INSTITUTION_TEACHER'
: 'INDIVIDUAL_TEACHER';
}
return accountType.toUpperCase() as AuthVariants;
}
See the picture. After I call the impersonate function it sets it to the impersonated mode but re-initializes itself and sets it to the default.
This is what I've tried:
Double Checked that proper dependencies were passed to the useEffect (it is not the one causing the re-initialize).
I was using a useStae before the reducer, and I was calling it via its function vs setting the state directly.
I tried stepping in (debugging) throughout the entire cycle, and didn't find anything.
I went through several SO posts and React dosc to see if I could find any issues, but my blinded eye couldn't see it.
Here's a view where I'm calling it from (See the const {impersonate} = useAuth()) :
import React, { memo, useCallback, useMemo, useState } from 'react';
import { RouteComponentProps } from '#reach/router';
import { Button, Typography } from 'components';
import Skeleton from 'react-loading-skeleton';
import { useAuth } from '../../../../../auth';
import { Tabs, Dialog } from '../../../../../components/';
import { useAllClassesAndTeacherForInstitution } from '../../../../../graphql';
import { useThemeSpacing } from '../../../../../shared-styles/material-ui';
import { AddClassTeacher, ListClassTeacher } from './components';
type TeacherViewRouteProps = {
teacherId: string;
};
export const TeacherView: React.FC<RouteComponentProps<
TeacherViewRouteProps
>> = memo((props) => {
const { impersonate } = useAuth();
const { teacherId } = props;
const { data, loading } = useAllClassesAndTeacherForInstitution(teacherId!);
const [open, setOpen] = useState(false);
const openDialog = useCallback(() => setOpen(true), []);
const closeDialog = useCallback(() => setOpen(false), []);
const spacing = useThemeSpacing(4)();
const teacherName = `${data?.teacher.name.fullName}`;
const impersonateTeacher = useCallback(() => {
if (!teacherName || !teacherId) {
return;
}
impersonate(teacherId!, 'teacher', teacherName);
closeDialog();
// props?.navigate?.('/');
}, [impersonate, closeDialog, teacherId, teacherName]);
const tabOptions = useMemo(
() => [
{
label: `Clases de ${teacherName}`,
},
{
label: 'Agregar Clases',
},
],
[teacherName],
);
return (
<>
<Typography variant="h1" className={spacing.marginTopBottom}>
{(loading && <Skeleton />) || teacherName}
</Typography>
<Dialog
title={`Entrar en la cuenta de ${teacherName}`}
open={open}
onAgree={impersonateTeacher}
onClose={closeDialog}
>
¿Desea visualizar la cuenta de {teacherName}?
<br />
Si desea salir de la misma por favor refresque la página.
</Dialog>
<Button className={spacing.marginTopBottom} onClick={openDialog}>
Entrar en cuenta de {teacherName || 'maestro'}
</Button>
{process.env.NODE_ENV === 'development' && (
<>
<Tabs options={tabOptions}>
<>
{data?.teacher.klasses && (
<ListClassTeacher
klasses={data.teacher.klasses}
teacherName={teacherName || 'maestro'}
/>
)}
</>
<>
{data?.grades && (
<AddClassTeacher
existingClasses={data?.teacher.klasses || []}
grades={data.grades}
teacherId={teacherId!}
/>
)}
</>
</Tabs>
</>
)}
</>
);
});
export default TeacherView;
Here's the initial Provider:
import React, { Suspense, memo } from 'react';
import { Location } from '#reach/router';
import { ThemeProvider } from '#material-ui/core';
import { ApolloProvider } from '#apollo/client';
import { theme } from 'components';
import { Auth0Provider } from '#auth0/auth0-react';
import CircularLoader from './components/CircularProgress';
import { useGlobalClient } from './utilities/client';
import { Layout } from './views/Layout';
import { Root } from './views/Root';
import { enableIfNotPreRendering } from './utilities/isPrerendering';
import { AUTH_CONFIG } from './auth/auth0.variables';
console.log('AUTH CONFIG', AUTH_CONFIG);
function App() {
// This will be a method to enable faster loading times.
/**\
* Main AppMethod which hosts the site. To improve FCP it was split into
* 2 files: The main file which will load the <Home component without any
* dependencies (making it extremely fast to load at the beginning as it won't)
* download all the code on its entirety.
*
* All consumers that are descendants of a Provider will re-render whenever the Provider’s value prop changes.
* The propagation from Provider to its descendant consumers is not subject to the
* shouldComponentUpdate method, so the consumer is updated even when an ancestor component
* bails out of the update.
*
* Check this out whenever you're planning on implementing offline capabilities:
* https://dev.to/willsamu/how-to-get-aws-appsync-running-with-offline-support-and-react-hooks-678
*/
return (
<Suspense fallback={<CircularLoader scrollsToTop={true} />}>
<Location>
{({ location }) => (
<Auth0Provider
{...AUTH_CONFIG}
location={{ pathname: location.pathname, hash: location.hash }}
>
<ProviderForClient />
</Auth0Provider>
)}
</Location>
</Suspense>
);
}
/**
* This is done like this because we are using the useAuth0 Hook
* and we need it to be after the Auth0Provider!!
* #param props
*/
export const ProviderForClient: React.FC = (props) => {
const globalClient = useGlobalClient();
return (
<ThemeProvider theme={theme}>
<ApolloProvider client={globalClient.current as any}>
<Layout>
<>{enableIfNotPreRendering() && <Root />}</>
</Layout>
</ApolloProvider>
</ThemeProvider>
);
};
export default memo(App);
I feel retarded. The hook was functioning normally. There's nothing wrong with the approach above (some other things can be debated). The problem was that I was not passing the hook via a context, but I was just calling the hook on each of the components. This meant that the hook was recreating the state (as it should be) per component, so whenever I updated the state, it would only be stated in one component.
That was it. I just had to rewrite the hook as a component and share it with a context.
Here's the final code (omitted some typings due to brevity)
const AuthContext = createContext<Context>({
isAuthenticated: false,
isLoading: false,
getAccessTokenSilently() {
return '' as any;
},
getAccessTokenWithPopup() {
return '' as any;
},
getIdTokenClaims() {
return '' as any;
},
loginWithPopup() {
return '' as any;
},
loginWithRedirect() {
return '' as any;
},
logout() {
return '' as any;
},
impersonate(a: string, b: AccountType, c: string) {},
exitImpersonation() {},
setSelectedTenantIndex(i: number) {},
accountType: 'teacher',
employeeId: '',
mode: 'NORMAL',
selectedTenant: {
accountType: 'teacher',
tenantType: 'INSTITUTION',
tenantId: '',
},
tenantId: '',
tenantType: 'INSTITUTION',
user: {
name: '',
nickname: '',
} as any,
variant: 'INSTITUTION_TEACHER',
});
/**
* A custom wrapper for Auth. This allows us to set impersonation
*/
export const Auth: React.FC = memo((props) => {
const { user: _user, isAuthenticated, isLoading, ...auth } = useAuth0();
const user = _user as Auth0HookUser;
const defaultUser = useCallback(
(user?: Auth0HookUser) => getDefaultAuthTenant(user),
[],
);
const [selectedTenantIndex, setSelectedTenantIndex] = useState(0);
const [state, dispatch] = useReducer<Reducer<State, Action>>(reducer, {
current: defaultUser(_user),
original: defaultUser(_user),
});
const calledDispatch = useCallback(dispatch, [dispatch]);
const impersonate = useCallback(
(
impersonatedEmployeeId: string,
accountType: AccountType,
impersonatedName: string,
) => {
if (!user) {
return;
}
calledDispatch({
type: 'IMPERSONATE',
accountType,
impersonatedEmployeeId,
impersonatedName,
});
},
[calledDispatch, user],
);
const exitImpersonation = useCallback(() => {
dispatch({ type: 'EXIT_IMPERSONATION' });
}, []);
useEffect(() => {
if (isLoading || (!isLoading && !isAuthenticated)) {
return;
}
if (!user || state.current.mode === 'IMPERSONATION') {
return;
}
const { tenants, userId } = user['https://app.schon.io/user_data'];
const selectedTenant = tenants[selectedTenantIndex];
const { accountType, tenantType } = selectedTenant;
dispatch({
type: 'UPDATE_AUTH',
auth: {
tenantId: selectedTenant.tenantId,
employeeId: userId,
mode: 'NORMAL',
variant: getVariant(accountType, tenantType),
user,
selectedTenant,
accountType,
tenantType,
},
});
// eslint-disable-next-line
}, [
user,
isAuthenticated,
isLoading,
selectedTenantIndex,
state.current.mode,
]);
return (
<AuthContext.Provider
value={{
isAuthenticated,
isLoading,
impersonate,
exitImpersonation,
setSelectedTenantIndex,
...auth,
...state.current,
}}
>
{props.children}
</AuthContext.Provider>
);
});
export function useAuth() {
const context = useContext(AuthContext);
if (!context) {
throw new Error(
'You need to place the AuthContext below the Auth0Context and on top of the app',
);
}
return context;
}
Now, I just placed the <Auth/> component on the top of my app.

Updating TabNavigator labels with data fetched from an API call

I have an app which has multiple stack navigators, one of which has a createMaterialTopTabNavigator inside it which shows me a list. Now for each of the tabs i get a count of the items inside it, i fetch these count through a separate API call (Count for all tabs is fetched through a single API). By default i am able to show a static tabLabel.
What i need to do is to show the count of each of the tabs in their labels(tab titles).
Navigator Code:
import React from "react";
import { View } from "react-native";
import { createMaterialTopTabNavigator } from "react-navigation";
import SellerListingScreen from "screens/App/SellerListingScreen/SellerListingScreen";
const SellerListingNavigator = createMaterialTopTabNavigator(
{
PendingSellers: {
screen: () => <SellerListingScreen type={0} />,
navigationOptions: {
title: "Pending(<show count here>)"
}
},
CompletedSellers: {
screen: () => <SellerListingScreen type={1} />,
navigationOptions: {
title: "Completed(<show count here>)"
}
}
},
{
tabBarOptions: {
style: {
backgroundColor: "#00cc99"
}
},
lazy: true
}
);
export default SellerListingNavigator;
With react-navigation, navigationOptions can be a static object like in your current example or a function that take an object containing the navigation object. In your case, you can easily rewrite your navigationOptions like this:
({navigation}) => {
const fetchDone = navigation.getParam('countFetchDone');
const currentCount = navigation.getParam('count');
if (!fetchDone) {
navigation.setParam('countFetchDone', true);
fetch(YOUR_FETCH_OPTIONS_HERE)
.then((r) => r.json())
.then((data) => {
navigation.setParam('count', data.count);
});
}
if (currentCount !== undefined) {
return {
title: 'My list (' + currentCount + ')'
};
} else {
return {
title 'My list (...)'
};
}
}
You need to save the state of the query as params so that the header updates correctly (as it updates only when params change). fetchDone is used to be sure the query is done once.
Ok i managed to solve it by creating a custom navigator white extending my existing tabNavigator & passing the required params to screenProps
import React from "react";
import { createMaterialTopTabNavigator } from "react-navigation";
// #ts-ignore
import SellerListingScreen from "screens/App/SellerListingScreen/SellerListingScreen";
// #ts-ignore
import { getItem } from "utils/interactAsyncStorage";
const SellerListingNavigator = createMaterialTopTabNavigator(
{
PendingSellers: {
screen: () => <SellerListingScreen type={0} />,
navigationOptions: ({ screenProps }) => ({
title: `Pending (${screenProps.pending})`
})
},
CompletedSellers: {
screen: () => <SellerListingScreen type={1} />,
navigationOptions: ({ screenProps }) => ({
title: `Completed (${screenProps.completed})`
})
}
},
{
tabBarOptions: {
style: {
backgroundColor: "#00cc99"
}
},
lazy: true
}
);
class customSellerListingNavigator extends React.Component {
constructor(props) {
super(props);
this.state = { pending: 0, completed: 0 };
}
static router = SellerListingNavigator.router;
_fetchPickupCounts = async () => {
const userData = await getItem("UserData");
const headers = {
"Content-Type": "application/json",
"Session-Token": userData.sessionToken,
};
const baseUrl = "baseurl here";
const url = `${baseUrl}/pickupCount/`;
return await fetch(url, {
method: "post",
headers: headers
})
.then(response => response.json())
.then(responseJson => {
this.setState({
pending: responseJson.pending,
completed: responseJson.completed
});
})
.catch(error => {
console.error(error);
});
};
componentDidMount() {
this._fetchPickupCounts();
}
render() {
const { navigation } = this.props;
return (
<SellerListingNavigator
navigation={navigation}
screenProps={{
pending: this.state.pending,
completed: this.state.completed
}}
/>
);
}
}
export default customSellerListingNavigator;

React native w/ redux: dispatch is not a function

I am trying to implement the following example in my project:
https://github.com/reactjs/redux/tree/master/examples/async
But I keep running into the error: dispatch is not function
when executing the dispatch function from my actions class.
It seems as if Dispatcher is not getting passed down to my actions but I followed the flow in the example:
actions/index.js file:
export const REQUEST_LOCAL_POSTS = 'REQUEST_LOCAL_POSTS';
export const RECEIVE_LOCAL_POSTS = 'RECEIVE_LOCAL_POSTS';
export const REQUEST_CURRENT_LOCATION = 'REQUEST_CURRENT_LOCATION';
export const RECEIVE_CURRENT_LOCATION = 'RECEIVE_CURRENT_LOCATION';
export const requestCurrentLocation = () => ({
type: REQUEST_CURRENT_LOCATION
})
export const receiveCurrentLocation = currentLocation => ({
type: RECEIVE_CURRENT_LOCATION,
currentLocation,
receivedCurrentLocationAt: Date.now()
})
export const requestLocalPosts = () => ({
type: REQUEST_LOCAL_POSTS
})
export const receiveLocalPosts = json => ({
type: RECEIVE_LOCAL_POSTS,
posts: json,
receivedAt: Date.now()
})
export const fetchLocalPosts = dispatch => {
dispatch(requestCurrentLocation())
navigator.geolocation.getCurrentPosition(
(position) => {
dispatch(requestLocalPosts()) // getting dispatch is not a function here
return fetch(`http://192.168.1.3:9000/posts?lng=${position.coords.longitude}&lat=${position.coords.latitude}&radius=1000`)
.then(response => response.json())
.then(json => dispatch(receiveLocalPosts(json)))
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
)
home.js (component):
import React, { Component } from 'react';
import {Text, View, ActivityIndicator, FlatList, Image, TouchableHighlight} from 'react-native';
import styles from './styles';
import MapView from 'react-native-maps';
import images from '../../config/images';
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { fetchLocalPosts } from '../../actions'
class Home extends Component {
static navigationOptions = ({ navigation }) => {
//const {dispatch , state, setParams} = navigation;
return {
title:<Text style={styles.title}>Localized</Text>,
headerStyle: {backgroundColor: '#2c6da4'},
headerRight: (
<TouchableHighlight onPress={() => navigation.dispatch({ type: 'MAP_EXPLORE' })}>
<Image
source={images.icons.map}
/>
</TouchableHighlight>
),
};
};
static propTypes = {
posts: PropTypes.array.isRequired,
isFetching: PropTypes.bool.isRequired,
lastUpdated: PropTypes.number,
dispatch: PropTypes.func.isRequired
}
componentDidMount() {
console.log(this.props)
const { dispatch } = this.props
dispatch(fetchLocalPosts()) // calling action from here
}
render() {
return (
<View style={styles.container}>
// i know posts isnt accessed here yet, still trying
to get past error
<FlatList
data={this.state.data}
refreshing={this.state.refreshing}
showsVerticalScrollIndicator={false}
ListHeaderComponent={this.renderHeader}
onRefresh={this._onRefresh.bind(this)}
renderItem={({item}) => <View><FlatList
data={item.posts}
horizontal={true}
snapToAlignment='center'
showsHorizontalScrollIndicator={false}
renderItem={({item}) => <Text style={styles.item}>{item.title}{"\n"}{item.snippet}</Text>}/>
<Text style={styles.subItem}>{item.Name}{"\n"}{item.Address}</Text>
</View>}
/>
</View>
);
}
}
const mapStateToProps = state => {
const { postsByBusiness } = state
const {
isFetching,
lastUpdated,
items: posts
} = postsByBusiness || {
isFetching: true,
items: []
}
return {
posts,
isFetching,
lastUpdated
}
}
export default connect(mapStateToProps)(Home)
reducer/index.js:
import { combineReducers } from 'redux';
import { NavigationActions } from 'react-navigation';
import { AppNavigator } from '../navigators/AppNavigator';
import { RECEIVE_LOCAL_POSTS, REQUEST_LOCAL_POSTS } from '../actions';
const initialNavState=AppNavigator.router.getStateForAction(NavigationActions.reset({
index: 0,
actions: [
NavigationActions.navigate({
routeName: 'Home',
}),
],
}));
const MAP_EXPLORE = 'MAP_EXPLORE';
const LIST_EXPLORE = 'LIST_EXPLORE';
function nav(state = initialNavState, action) {
let nextState;
switch(action.type) {
case MAP_EXPLORE:
nextState = AppNavigator.router.getStateForAction(
NavigationActions.navigate({ routeName: 'Map'}),
state
);
break;
case LIST_EXPLORE:
nextState = AppNavigator.router.getStateForAction(
NavigationActions.navigate({ routeName: 'List'}),
state
);
break;
default:
nextState = AppNavigator.router.getStateForAction(action, state);
break;
}
return nextState || state;
}
function postsByBusiness(state = { }, action) {
switch(action.type) {
case RECEIVE_LOCAL_POSTS:
return {
...state,
isFetching: false,
didInvalidate: false,
items: action.posts,
lastUpdated: action.receivedAts
}
default:
return state
}
}
const AppReducer = combineReducers({
nav,
postsByBusiness
});
export default AppReducer;
fetchLocalPosts should be returning a function that takes dispatch as an argument. Changing it to the following should fix it.
export const fetchLocalPosts = () => dispatch => {
...
It's another way of doing this:
export const fetchLocalPosts = () => {
return function (dispatch) {
...

Categories