Edited the post!!!
id comeing trough login request, at the else branch at handleChangeId! it gets the correct id! i try to push at the top!
export function Login({handleChangeId}) {
const login = () => {
//node port egyezés szükséges
Axios.post('http://localhost:3001/login', {
LoginUsername: usernameLog,
LoginPassword: passwordLog,
}).then((response) => {
if (response.data.message) {
setLoginCorrect(response.data.message)
}
else {
handleChangeId(response.data[0].id);
navigate("/App");
}
});
};
}
than at App.js i try to get the id from the login Route, and push trough profile Route
let id = null;
function changeID(newId) {
id= newId;
}
ReactDOM.render(
<BrowserRouter>
<Routes>
<Route exact path="/" element={<Login handleChangeId={changeID} />}
<Route exact path="/profile" element={<Profile id={id} />} />
</Routes>
</BrowserRouter>,
document.getElementById('root')
); />
at Profile.js, i also try to get the id this way, but the value=null every way that i tried! And this is what im looking for - how to read and set the id and get their personal datas, when the users hit profile on the menubar!
export function Profile({ id }) {
const [costumers, setCostumers] = useState([]);
useEffect(() => {
Axios.get(`http://localhost:3001/profile?userId=${id}`)
.then((response) => {
if (response) {
setCostumers(response.data);
}
else {
alert("Datas currently unavailable!")
}
});
}, []);
}
CodePudding user response:
Issue
let id = null; function changeID(newId) { id= newId; }
Doesn't work because id
is declared each render cycle with a null value, and simply mutating it doesn't trigger a component rerender with the updated value to be passed to the Profile
component.
Solution
Make id
part of the component state so updating it triggers a rerender with the updated value closed over in scope.
Example:
const [id, setId] = React.useState(null);
...
const changeID = (newId) => {
setId(newId);
}
...
<Routes>
<Route path="/" element={<Login handleChangeId={changeID} />}
<Route
path="/profile"
element={<Profile id={id} />} // <-- updated id state value passed here
/>
</Routes>