React useState() doesn't update value synchronously [duplicate] - html

This question already has answers here:
The useState set method is not reflecting a change immediately
(15 answers)
Closed last year.
React useState() doesn't update value of the variable if called just after setting value.
I read about useEffect(), but don't really know how this will be useful for this particular scenario.
Full code (please open the console tab to see the variable status)
UPDATE
// hook
const [ error, setError ] = useState<boolean>();
const handleSubmit = (e: any): void => {
e.preventDefault();
if (email.length < 4) {
setError(true);
}
if (password.length < 5) {
setError(true);
}
console.log(error); // <== still false even after setting it to true
if (!error) {
console.log("validation passed, creating token");
setToken();
} else {
console.log("errors");
}
};

Let's assume the user does not have valid credentials. The problem is here:
if (email.length < 4) { // <== this gets executed
setError(true);
}
if (password.length < 5) { // <== this gets executed
setError(true);
}
console.log(error); // <== still false even after setting it to true
if (!error) { // <== this check runs before setError(true) is complete. error is still false.
console.log("validation passed, creating token");
setToken();
} else {
console.log("errors");
}
You are using multiple if-checks that all run independently, instead of using a single one. Your code executes all if-checks. In one check, you call setError(true) when one of the conditions is passed, but setError() is asynchronous. The action does not complete before the next if-check is called, which is why it gives the appearance that your value was never saved.
You can do this more cleanly with a combination of if-else and useEffect instead: https://codesandbox.io/s/dazzling-pascal-78gqp
import * as React from "react";
const Login: React.FC = (props: any) => {
const [email, setEmail] = React.useState("");
const [password, setPassword] = React.useState("");
const [error, setError] = React.useState(null);
const handleEmailChange = (e: any): void => {
const { value } = e.target;
setEmail(value);
};
const handlePasswordChange = (e: any): void => {
const { value } = e.target;
setPassword(value);
};
const handleSubmit = (e: any): void => {
e.preventDefault();
if (email.length < 4 || password.length < 5) {
setError(true);
} else {
setError(false);
}
};
const setToken = () => {
//token logic goes here
console.log("setting token");
};
React.useEffect(() => {
if (error === false) {
setToken();
}
}, [error]); // <== will run when error value is changed.
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="email#address.com"
onChange={handleEmailChange}
/>
<br />
<input
type="password"
placeholder="password"
onChange={handlePasswordChange}
/>
<br />
<input type="submit" value="submit" />
</form>
{error ? <h1>error true</h1> : <h1>error false</h1>}
</div>
);
};
export default Login;

Just like setState, useState is asynchronous and tends to batch updates together in an attempt to be more performant. You're on the right track with useEffect, which would allow you to effectively perform a callback after the state is updated.
Example from the docs:
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Although it is also recommended that if you need the updated value as soon as an update to the state has been requested, you're likely better off with just a variable in the component.
More on using state synchronously
And if you're familiar with Redux's reducers, you could use useReducer as another alternative. From the docs:
useReducer is usually preferable to useState when you have complex
state logic that involves multiple sub-values or when the next state
depends on the previous one. useReducer also lets you optimize
performance for components that trigger deep updates because you can
pass dispatch down instead of callbacks.

Related

Taken two pages back since render function is called twice

I want to go back to the previous page when Apollo Client error.graphQLErrors has an error with a specific message from the back-end server,
Below is the snippet of my code.
const Detail = () => { const { snackbar } = useSnackbar();
const history = useHistory();
return(
<Compo query={graphQLQuery}>
{({ data, error, }) => {
if(error?.graphQLErrors[0]?.extensions?.debugMessage.includes('Specific Error')){
history.goBack();
snackbar('Specific Error');
return <></>;
}
else{
//render another component
}
}
}
</Compo>);
Issue is since the render is called twice, when the error happens, history.goBack() is executed twice and I'm taken two pages back.
I'm able to avoid this by removing <React.StrictMode> encapsulating <App> component.
Is there a better way to do this?
I'm trying to avoid removing <React.StrictMode> since it's been there since a long time.
Issue
The issue here is that you are issuing an unintentional side-effect from the render method. In React function components the entire function body is considered to be the "render" method. Move all side-effects into a useEffect hook.
Solution
Since the code is using a children function prop you'll need to abstract what the "child" is rendering into a React component that can use React hooks.
Example:
const DetailChild = ({ data, error }) => {
const history = useHistory();
const { snackbar } = useSnackbar();
const isErrorCondition = error?.graphQLErrors[0]?.extensions?.debugMessage.includes('Specific Error'
useEffect(() => {
if (isErrorCondition)) {
history.goBack();
snackbar('Specific Error');
}
}, [error]);
return isErrorCondition
? null
: (
... render another component ...
);
};
...
const Detail = () => {
return (
<Compo query={graphQLQuery}>
{({ data, error }) => <DetailChild {...{ data, error }} />}
</Compo>
);
};

i want to redirect user after login based on their role and stop them to access this page in React.js

I had did this using Redux library and MongoDB and its works fine with this but now i am doing same thing with mysql so its not working well. This logic always redirect all users to admin dashboard. i want do like, if i do isAdmin="true" it will redirect to admin dashboard and stop to going coordinator dashboard. and if isCoordinator="true" then redirect to coordinator dashboard and not able to access admin dashboard. how can i that?
*This is my Admin.js file. where i did logic to private access path.
import { useSelector } from "react-redux";
import { Route, Routes, Link, useNavigate } from "react-router-dom";
import UsersList from "./UsersList";
import UsersEntry from "./UsersEntry";
import Projects from "./projects/Projects";
import "./Admin.css"
export default function Admin() {
let navigate = useNavigate();
const userState = useSelector(state=> state.loginUserReducer)
const {currentUser} =userState;
useEffect(() => {
// This code check Role of user who logged in and if not coordinator then restrict(stop) to going on this private page. By getItem and check === !currentUser.isCoordinator.
if(localStorage.getItem('currentUser') === null || !currentUser.isAdmin){
navigate('/coordinators');
if(localStorage.getItem('currentUser') === null || !currentUser.isCoordinator){
navigate('/');
}
}
}, [])
*This is UserAction.js fie.
export const loginUser = (user) => async (dispatch) => {
dispatch({type: "USER_LOGIN_REQUEST"});
try {
const response = await axios.post("http://localhost:4000/login",user);
console.log(response.data);
dispatch({type:"USER_LOGIN_SUCCESS", payload: response.data});
localStorage.setItem('currentUser',JSON.stringify(response.data));
window.location.href = "/admin";
} catch (error) {
dispatch({type: "USER_LOGIN_FAIL", payload: error})
}
}
*This is UserReducer.js.
switch (action.type){
case "USER_LOGIN_REQUEST":
return{
loading:true,
};
case "USER_LOGIN_SUCCESS":
return{
success: true,
loading: false,
currentusers: action.payload,
};
case "USER_LOGIN_FAIL":
return{
error: action.payload,
loading:false,
};
default:
return state;
}
};
*This is Store.js.
import thunk from 'redux-thunk';
import {composeWithDevTools} from 'redux-devtools-extension';
import {loginUserReducer} from './UserReducer';
const currentUser = localStorage.getItem('currentUser') ? JSON.parse(localStorage.getItem('currentUser')) : null
const rootReducer = combineReducers({loginUserReducer : loginUserReducer});
const initialState = {
loginUserReducer: {
currentUser : currentUser
}
}
const middleware = [thunk]
const store = createStore(
rootReducer,
initialState,
composeWithDevTools(applyMiddleware(...middleware))
);
export default store;
In your useEffect inside the dependency array pass the currentUser so whenever it is changed useEffect will be triggered. In current scenario when the array is empty it just happens on the page load the very first time.
Here is the possible thing to try:
useEffect(() => {
// This code check Role of user who logged in and if not coordinator then restrict(stop) to going on this private page. By getItem and check === !currentUser.isCoordinator.
if(localStorage.getItem('currentUser') === null || !currentUser.isAdmin){
navigate('/coordinators');
if(localStorage.getItem('currentUser') === null || !currentUser.isCoordinator){
navigate('/');
}
}
}, [currentUser]) <================
Secondly also check your nested if condition. You can use an else if as well so incase its not admin it will go inside if and if it is admin then it can go inside the else if block. But that is totally up to you, just a suggestion.

React Admin - Redirecting to a page after login

I have a react admin application with a customRoutes, as well as resources (say /users). One of my custom route is a private page (say /private), which I protect with the useAuthenticated() hook:
export default () => {
useAuthenticated();
return (<Card>
<Title title="Private Page" />
<CardContent>
This is a private page.
</CardContent>
</Card>)
}
When I browse this private page and I'm not authenticated, I'm entering an authentication process as it should be (I'm using OIDC). This process is triggered by the checkAuth() method of the authProvider. But when the process is completed, I'm redirected to the /users resource and not the /private page. Is there a way to tell the authProvider that I want to be redirected to the private page?
Thanks - C
I have not done this myself, but I imagine you can use your redirect path as an argument in the useAuthenticated() call. https://marmelab.com/react-admin/Authentication.html#useauthenticated-hook
export default () => {
useAuthenticated({ redirectPath: '/privatepage' });
return (
<Card>
<Title title="Private Page" />
<CardContent>
This is a private page.
</CardContent>
</Card>
)
}
From there you should be able to use that arg/parameter in your checkAuth method.
tl;dr In your login().then() aspect, do a redirect('/myDefaultUrl')
I had the same challenge as you, I think. After looking into the ReactAdmin code a bit I was unable to find a way to do it in any 'official' way. I did see something quite interesting in the useAuthProvider() hook.
The AuthProvider object maintained by RA seems to have a variable with a couple properties initialized with some defaults.
import { useContext } from 'react';
import { AuthProvider } from '../types';
import AuthContext from './AuthContext';
export const defaultAuthParams = {
loginUrl: '/login',
afterLoginUrl: '/',
};
/**
* Get the authProvider stored in the context
*/
const useAuthProvider = (): AuthProvider => useContext(AuthContext);
export default useAuthProvider;
Specifically the afterLoginUrl property looked interesting. I attempted to override that property in my authProvider but didn't have any luck.
What I ended up doing was this. In my invocation of the login (from useLogin()), when the authProvider.login resolves, I return back the user along with their profile (I use Cognito so it is a CognitoUser instance). In my user I have configured an attribute for where the user should go after login. I then simply use the redirect hook (from useRedirect) to then direct the user to that URL.
Here is my login from my AuthProvider:
const authProvider = {
login: (params) => {
if (params instanceof CognitoUser) {
return params;
}
if (params.error) {
return Promise.reject(params.error);
}
return new Promise((resolve, reject) => {
Auth.signIn(params.username,params.password).then(cognitoUser => {
if (cognitoUser.challengeName === 'NEW_PASSWORD_REQUIRED') {
reject({ code: 'NewPasswordRequired', cognitoUser: cognitoUser })
} else {
setAndStoreUserProfile(cognitoUser);
resolve(cognitoUser);
}
}, function(err) {
reject(err);
});
});
},
....
Then in my Login form, I do this:
raLogin(formData)
.then((cognitoUser) => {
console.log("User logged in. Result:", cognitoUser);
clearTransitionState();
redirect('/profile');
})
.catch(error => {
if (error.code && error.code === 'PasswordResetRequiredException') {
transition(PHASE.RESET_ACCOUNT, {username: formData.username });
} else if (error.code && error.code === 'NewPasswordRequired') {
transition(PHASE.NEW_PASSWORD, { cognitoUser: error.cognitoUser });
} else {
processAuthError(error);
}
});

TypeScript - Navigate dropdown listitems using keyboard

I'm working on an open-source project and have encountered a bug. I'm not able to navigate the dropdown list items using the keyboard (arrow key/tab). I've written the keyboard-navigation logic, but not quite sure of how to implement it. Below is the code snippet.
.
.
.
const TopNavPopoverItem: FC<ComponentProps> = ({closePopover, description, iconSize, iconType, title, to}) => {
const history = useHistory();
const handleButtonClick = (): void => {
history.push(to);
closePopover();
};
const useKeyPress = function (targetKey: any) { // where/how am I supposed to use this function?
const [keyPressed, setKeyPressed] = useState(false);
function downHandler(key: any) {
if (key === targetKey) {
setKeyPressed(true);
}
}
const upHandler = (key: any) => {
if (key === targetKey) {
setKeyPressed(false);
}
};
React.useEffect(() => {
window.addEventListener('keydown', downHandler);
window.addEventListener('keyup', upHandler);
return () => {
window.removeEventListener('keydown', downHandler);
window.removeEventListener('keyup', upHandler);
};
});
return keyPressed;
};
return (
<button className="TopNavPopoverItem" onClick={handleButtonClick}>
<Icon className="TopNavPopoverItem__icon" icon={iconType} size={iconSize} />
<div className="TopNavPopoverItem__right">
<span className="TopNavPopoverItem__title">{title}</span>
<span className="TopNavPopoverItem__description">{description}</span>
</div>
</button>
);
};
Any workaround or fixes?
Thanks in advance.
A custom hook should always be defined at the top level of your file. It cannot be inside of a component. The component uses the hook, but doesn't own the hook.
You have a hook which takes a key name as an argument and returns a boolean indicating whether or not that key is currently being pressed. It's the right idea, but it has some mistakes.
When you start adding better TypeScript types you'll see that the argument of your event listeners needs to be the event -- not the key. You can access the key as a property of the event.
(Note: Since we are attaching directly to the window, the event is a DOM KeyboardEvent rather than a React.KeyboardEvent synthetic event.)
Your useEffect hook should have some dependencies so that it doesn't run on every render. It depends on the targetKey. I'm writing my code in CodeSandbox where I get warnings about "exhaustive dependencies", so I'm also adding setKeyPressed as a dependency and moving the two handlers inside the useEffect.
I see that you have one handler as function and one as a const. FYI it really doesn't matter which you use in this case.
Our revised hook looks like this:
import { useState, useEffect } from "react";
export const useKeyPress = (targetKey: string) => {
const [keyPressed, setKeyPressed] = useState(false);
useEffect(
() => {
const downHandler = (event: KeyboardEvent) => {
if (event.key === targetKey) {
setKeyPressed(true);
}
};
const upHandler = (event: KeyboardEvent) => {
if (event.key === targetKey) {
setKeyPressed(false);
}
};
// attach the listeners to the window.
window.addEventListener("keydown", downHandler);
window.addEventListener("keyup", upHandler);
// remove the listeners when the component is unmounted.
return () => {
window.removeEventListener("keydown", downHandler);
window.removeEventListener("keyup", upHandler);
};
},
// re-run the effect if the targetKey changes.
[targetKey, setKeyPressed]
);
return keyPressed;
};
I don't know you intend to use this hook, but here's a dummy example. We show a red box on the screen while the spacebar is pressed, and show a message otherwise.
Make sure that the key name that you use when you call the hook is the correct key name. For the spacebar it is " ".
import { useKeyPress } from "./useKeyPress";
export default function App() {
const isPressedSpace = useKeyPress(" ");
return (
<div>
{isPressedSpace ? (
<div style={{ background: "red", width: 200, height: 200 }} />
) : (
<div>Press the Spacebar to show the box.</div>
)}
</div>
);
}
CodeSandbox Link

how to mock on global object in backstop.js/puppetter

So backstop.js provides ability to run custom script against underlying engine. I use puppeteer as an engine so I try to mock Date.now with 'onReadyScript':
page.evaluate('window.Date.now = () => 0; Date.now = () => 0;');
...
page.addScriptTag({
// btw `console.log` here is not executed, do I use it in wrong way?
content: 'Date.now = () => 0;'
});
...
page.evaluate(() => {
window.Date.now = () => 0;
Date.now = () => 0;
});
Last one, I think, is modifying Date in context of Node, not inside the puppeteer, but anyway tried that as well.
Nothing worked, script under the test still output real Date.now. Also I checked Override the browser date with puppeteer but it did not help me.
Yes, I know I'm able to skip particular selectors, but it does not always make sense(think about clock with arrows).
After trying onBeforeScript with evaluateOnNewDocument() it works for me. Complete script:
module.exports = async function (page, scenario) {
if (!page.dateIsMocked) {
page.dateIsMocked = true
await page.evaluateOnNewDocument(() => {
const referenceTime = '2010-05-05 10:10:10.000';
const oldDate = Date;
Date = function(...args) {
if (args.length) {
return new oldDate(...args);
} else {
return new oldDate(referenceTime);
}
}
Date.now = function() {
return new oldDate(referenceTime).valueOf();
}
Date.prototype = oldDate.prototype;
})
}
};
Reason: onReadyScript is executed when page under testing has already been loaded and executed. So code is bound to original Date by closure, not the mocked version.