Search code examples
reactjsasynchronouslocal-storagesynchronous

localStorage.getItem / .setItem is async?


i've latelty started with react and wanted to make a login logic. Have been struggling with it for a while and finally stumbled on the localStorage. What i tried to do was after getting user credentials from api, store them in localStorage for page redirection based on user authorization.

The problem is localStorage seems to be async. I call localStorage before if and if is executed first, based on prev data in localStorage.

SignIn.js

 let permission_type;
                    switch (res.data.permission){
                        case 1:
                            permission_type='supervisor';
                            break;
                        case 2:
                            permission_type='basicuser';
                            break;
                        case 3:
                            permission_type='qualitychecker';
                            break;
                        default:
                            permission_type='guest';
                            break;

                    }
                    let newUserData={id: userData.id,
                                auth: permission_type}

                    localStorage.setItem("signed-in-user", JSON.stringify(newUserData));
                    history.push(`/${permission_type}`);

//

Home.js

const Home = () => {

const [user, setUser] = useState({});
const history = useHistory();

useEffect(() => {
    const us = JSON.parse(localStorage.getItem('signed-in-user'));
    setUser(us);
});

const signOut = () => {
    const signOutUser = {id: -1,
                        auth: 'guest'}
    localStorage.setItem('signed-in-user',JSON.stringify(signOutUser));
    localStorage.clear();
    history.push('/');
}

const classes = useStyles();
console.log(user.auth)
if (user.auth == 'basicuser') {return (
  <div>
    <AppBar position="static">
      <Toolbar>
        <IconButton edge="start"
                    className={classes.menuButton}
                    color="inherit"
                    aria-label="menu">
            <MenuIcon />
        </IconButton>
        <Typography variant="h6"
                    className={classes.title}>
            News
        </Typography>
        <Button color="inherit"
                onClick={signOut}>SIGN OUT</Button>
      </Toolbar>
    </AppBar>
  </div>
);}
else {
  return (<Redirect to='/' />);
}

};


Solution

  • localstorage functions are sync. What you say must be "thread-safe". localstorage is not thread-safe. Need something to lock data, if you want.