lets say I have this login form
<form>
<label>
<p>Username</p>
<input type="text" />
</label>
<label>
<p>Password</p>
<input type="password" />
</label>
<div>
<button type="submit">Submit</button>
</div>
<div>
<span>{errMsg}</span>
</div>
</form>
with errMsg is from useState hook that will be changed when user fail to login. How do I make the state of errMsg back to empty or "" when user move to another page then come back? useEffect doesn't work here because when the errMsg is updated it will re-render the component and makes the errMsg empty.
CodePudding user response:
Include a state in this component. When there is an error, state will be true. And if no error state will be false. Initially it will be false. When user comes back to this page the component will re-render and the state will be false.
const [isError, setIsError] = useState(false);
//if error then set isError to true
//in UI check this
<div>
<span>{isError ? errMsg : ""}</span>
</div>
Or if you use the state in parent component, then try to replicate functionality of "componentWillUnmount" lifecycle using "useEffect" hook. When the component gets unmounted (user goes to another page), the state will set to false.