'How to make an arrow function in react so that it executes only once and saves the data in sessionStorage
I am developing an application in react.js and I need to implement a request to Active directory to extract the information of the logged in user, through Microsoft graph. I occupy to eliminate the use of the button and the onclick and that the function is executed only once. I need help in react for this function to execute only once and save the data in sessionStorage.
function ProfileContent() {
const { instance, accounts } = useMsal();
const [graphData, setGraphData] = useState(null);
const name = accounts[0] && accounts[0].name;
function RequestProfileData() {
const request = { ...loginRequest, account: accounts[0] };
sessionStorage.setItem('name', request['account']['name']);
sessionStorage.setItem('username', request['account']['username']);
localStorage.setItem('name', request['account']['name']);
localStorage.setItem('username', request['account']['username']);
// Silently acquires an access token which is then attached to a request for Microsoft Graph data
instance.acquireTokenSilent(request).then((response) => {
callMsGraph(response.accessToken).then(response => setGraphData(response));
}).catch((e) => {
instance.acquireTokenPopup(request).then((response) => {
callMsGraph(response.accessToken).then(response => setGraphData(response));
});
});
}
return (
<>
<h5 className="card-title">Welcome {name}</h5>
<h5> {name}</h5>
{graphData ?
<ProfileData graphData={graphData} />
:
<Button variant="secondary" onClick={RequestProfileData}>Request Profile information</Button>
}
</>
);
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|