what u see below is my App.js Component
export default function App() {
const [userData, setUserData] = useState(null);
useEffect(() => {
try {
const jwt = localStorage.getItem("token");
const user = jwtDecode(jwt);
console.log("user", user);
setUserData(user);
console.log("emp1", userData);
} catch (ex) {}
});
console.log("emp2", userData);
render(
<BrowserRouter>
<ToastContainer
rtl
position="top-left"
style={{ width: 520, fontSize: 15 }}
/>
<div className="App">
<Navbar userData={userData} />
</div>
</BrowserRouter>,
document.getElementById("root")
);
}
as u see on the top i defined null value for my state and i want to update the state with the object that i get from the decoded token but i dont know why state does not update?
NOTE: i want to send the state as a props to the Navber.js Component
You need to set dependency array in useEfect:
useEffect(() => {
try {
const jwt = localStorage.getItem("token");
const user = jwt.decode(jwt);
setUserData(user);
console.log("emp1", userData);
} catch (ex) {}
}, []);
[] in useEffect means:
If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run. This isn’t handled as a special case — it follows directly from how the dependencies array always works.
UPDATE:
You need to use jwt.decode(token) not jwtDecode:
useEffect(() => {
try {
const jwt = localStorage.getItem("token");
const user = jwt.decode(jwt);
setUserData(user);
console.log("emp1", userData);
} catch (ex) {}
}, []);
I've created an example how it is possible to send data to functional component at Stackblitz.