I have a request to authenticate my web page on Salesforce Marketing Cloud, the authentication must made and store only once.
My Problem is, when I request to authenticate and get a code I am getting two request, 1st request is successful and the 2nd request is error.
Question why am I getting two request one useEffect on react js? is my component loaded twice?
Here is my code:
useEffect(() => {
async function initialize() {
const params = await getParamsFromUrl();
if (params.code) {
await getTokenAndSaveToSession(params.code);
await fetchJourneyData(); // Renamed the function to make it clearer
} else {
console.log('There is no code in the params');
}
}
initialize();
}, []); // The empty dependency array ensures that the effect runs only once on mount
async function getTokenAndSaveToSession(code: string) {
try {
const authService = new AuthService();
const result = await authService.getToken(code);
sessionStorage.setItem('token', result.token);
sessionStorage.setItem('expiration', result.expiration.toString());
} catch (error) {
console.log(error);
}
}
2
Answers
According to React docs, in development, React mounts your components twice to ensure that your component rendering is pure.
For your case, if the server you are making a request to only allows request once, you may want to handle the case when your component makes the second request, so that it reuses the authentication code already obtained in the first request.
Because you are using
<StrictMode>
.[react-docs] The result is thatuseEffect
runs twice thereby making your api call twice. If you don’t not want these extra development checks, simply remove<StrictMode>
(not advised) or controluseEffect
.