Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making SessionStorage calls using async await in React

I have a functional Component that has the following code.

import { isUserAuthCheck } from "../../Utils/SessionStorage";

function DefaultPage({ history }) {
  useEffect(() => void (isUserAuthCheck ? history.push("/home") : null));

and in my Utils/SessionStorage, I have the following

export const isUserAuthCheck =
  sessionStorage.getItem("isUserAuthenticated") === "true";
export const getIsUserAuthenticated = sessionStorage.getItem(
  "isUserAuthenticated"
);
export const setValueInSession = (key, value) =>
  sessionStorage.setItem(key, value);

export const setIsUserAuthenticated = str =>
  sessionStorage.setItem("isUserAuthenticated", str);

Problem here is, isUserAuthCheck doesn't seem to update every time there's a change in sessionStorage. How can I make sure that it's getting updated every time there's a change in sessionStorage.

Any help is appreciated.

like image 528
Sai Krishna Sanka Avatar asked Mar 24 '26 06:03

Sai Krishna Sanka


1 Answers

Because it is not a function. It doesn't fire the checking everytime you call it. You have to make it a function to run the checking AGAIN.

export const isUserAuthCheck = () =>
  sessionStorage.getItem("isUserAuthenticated") === "true";

Or you can update it everytime you set value for isUserAuthenticated, but it is a const so you'd have to change it.

EDIT:

If you want it to be a getter as i mentioned:

enter image description here

Also avoid using "true" or any kind of these things. There is a reason why bool type is available

like image 183
sshanzel Avatar answered Mar 25 '26 18:03

sshanzel