Background:
After logging in to user A from the same browser. A new TAB page is displayed, and user B is logged in. At this time, because user A’s login information has been updated by user B, the data is incorrect, and such A problem is raised.
Our solution is: after logging in to user B, when switching back to user A’s browser TAB, we will prompt that A new user has logged in, and then refresh the page again.
Code implementation
Provide an NPM method for the project team to call after logging in to retrieve user information. Of course, the premise is that the user information depends on the local cache of localStorage.
export default (storageKeyString: string, seconds: number = 2, tipsCallFunction? :() = >= > {{})if (typeofseconds ! = ='number' ) throw new Error('seconds should be number');
let cacheValue = getStorageVale(storageKeyString);
if (document.hidden ! = =undefined) {
document.addEventListener('visibilitychange'.() = > {
if (!document.hidden) {
let currentValue = getStorageVale(storageKeyString);
if(currentValue ! == cacheValue) {if (tipsCallFunction && typeof tipsCallFunction === 'function') {
tipsCallFunction();
} else {
window.alert('Detect new user login, current page will refresh after 2s! ');
}
setTimeout(() = > {
window.location.reload();
}, seconds * 1000}}})}}function getStorageVale (storageKeyString: string) {
var [localstorage, ...restKeyArrays] = storageKeyString.split('. ');
let localStorageInfo = window.localStorage.getItem(localstorage)
if(! restKeyArrays.length)return localStorageInfo;
let returnVal = JSON.parse(localStorageInfo || '{}');
for(let i = 0; i < restKeyArrays.length; i++ ) {
returnVal = returnVal[restKeyArrays[i]]
if(! returnVal)return ' ';
if (typeof returnVal === 'string') {
return returnVal
}
}
return ""
}
Copy the code
Usage:
Install and use
npm install --save @bit-sun/business-component@1.1. 0
Copy the code
The demo code
import React, { useRef } from 'react';
import { message } from 'antd';
import { CheckOneUser } from '@bit-sun/business-component';
CheckOneUser('userInfo.a.information.name'.3.() = > {
message.warning('Detect new user login, current page will refresh after 3s! ');
})
export default() = > {return (
<div>
</div>
);
};
Copy the code
Attributes that
CheckOneUser(
storageKeyString: string,
seconds: number = 2, tipsCallFunction? :() = >{})Copy the code
The property name | type | The default value |
---|---|---|
storageKeyString | string: ‘userInfo.a.information.name’ | There is no |
seconds | number | 2 |
tipsCallFunction | function | () = > { Window. alert(‘ Detect new user login, current page will refresh after 2s! ‘) } |
StorageKeyString instructions
‘the userInfo. Anderson, nformation. The name’ : the user for the item name, other property access
Demonstrate the demo
Demo code effect display