'function execution in Reactjs
i have problem in app.js component . It goes like this when I login in application then the token is stored in local storage and Getcompany function is called with Authorization(token).But My Permission function will not run along with getcompany function .It will run only whole component is reloaded again and I don't know why console.log(_token) willnot show token value when i login in application. i am getting spinner message"Loading Permission" when i login to application then i have to reload the component then it provides me all Permissions from API. Could anybody help me?
function App() {
const [token, setToken] = useState();
const [companies, setAllCompanies] = useState();
const [permissions, setPermissions] = useState();
const [company, setCompany] = useState();
const save_token = (e) => {
window.localStorage.setItem("TOKEN", e);
setToken(e);
};
console.log(token)
useEffect(() => {
let _token = window.localStorage.getItem("TOKEN");
console.log(_token)
if (_token === undefined || _token === null)
{
setToken(false);
} else {
setToken(_token);
getCompanies(_token);
}
}, []);
const getCompanies = (_token) => {
fetch(`${config.APP_CONFIG}/Companies/Company`, {
headers: {
Authorization: _token,
"Content-Type": "application/json",
},
})
.then((res) => res.json())
.then((res) => {
if (res.status_code === 401) {
handleLogOut();
} else if (res.status_code === 200) {
setAllCompanies(res.msg);
if (res.msg.length > 0) {
setCompany(res.msg[0]);
getPermissions(_token);
} else {
setCompany([]);
}
} else {
toast.error("cannot fetch Companies");
setAllCompanies([]);
}
})
.catch((err) => {
toast.error("error fetching Companies");
setAllCompanies([]);
});
};
const getPermissions = (__token) => {
axios .get(`${config.APP_CONFIG}/UserPermission/getUserPermission/${__token}`)
.then((res) => {
if (res.data.status_code === 200) {
setPermissions(res.data.msg)
} else {
toast.error("Error Loading Permission");
setPermissions([]);
}
})
.catch((err) => {
console.log(err);
toast.error("cannot fetch Permission");
setPermissions([]);
});
};
if (token === undefined) {
return <Spinner msg="Authenticating..." />;
}
if (token === false) {
return (
<div>
<ToastContainer rtl />
<Login setToken={save_token}></Login>
</div>
);
}
if (companies === undefined) {
return <Spinner msg="Loading companies..." />;
}
if (company === undefined) {
return <Spinner msg="Initializing..." />;
}
if (permissions === undefined) {
return <Spinner msg="Loading permissions..." />;
}
Solution 1:[1]
Calls to setState() are asynchronous, so you're probably accessing the state variable before it's been updated with the correct value from localStorage.
You should refactor your code to listen for changes to the token variable (which can be achieved by passing it as a dependency to a useEffect() hook call) as follows:
useEffect(() => {
let _token = window.localStorage.getItem("TOKEN");
if (_token === undefined || _token === null) {
setToken(false);
} else {
setToken(_token);
}
}, []);
useEffect(() => {
if (token) {
fetch(`${config.APP_CONFIG}/Companies/Company`, {
headers: {
Authorization: token,
"Content-Type": "application/json",
},
}).then((res) => res.json())
.then((res) => {
if (res.status_code === 401) {
handleLogOut();
} else if (res.status_code === 200) {
setAllCompanies(res.msg);
if (res.msg.length > 0) {
setCompany(res.msg[0]);
} else {
setCompany(null);
}
} else {
toast.error("cannot fetch Companies");
setAllCompanies([]);
}
})
.catch(() => {
toast.error("error fetching Companies");
setAllCompanies([]);
});
// Now get the permissions:
axios .get(`${config.APP_CONFIG}/UserPermission/getUserPermission/${token}`)
.then((res) => {
if (res.data.status_code === 200) {
setPermissions(res.data.msg)
} else {
toast.error("Error Loading Permission");
setPermissions([]);
}
}).catch((err) => {
console.log(err);
toast.error("cannot fetch Permission");
setPermissions([]);
});
}
}, [ token ]);
Given the above, whenever the value of token changes, the companies and permissions will be fetched again from your server using the new token value (assuming it's not falsey).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BenM |
