- I have multiple routes, by default app open in
"/login"
endpoint which renders<Loginpage />
- when I enter username and password the code in
<Loginpage />
validates the credentials with the api it is fetching from localhost, - Now when I am seeing
<LoginPage />
and click sumbit, I am seeing
immediate url changing and later seeing data manipulating acc to
activeuser state.
What I want
-
But, I want to render
<Loading/>
component when the api is being
fetched, as soon it fetches I want to redirect to homepage endpointAnd also,
<NavbarModule />
should be rendered in create bill and homepage components, but I don’t want it in<Loginpage />
, for this I came up with a solution by placing<NavbarModule/>
in both create bill and homepage routes, But I feel its bit repeating code, Help me with these 2 problems
function App() {
const [activeUser, setActiveuser] = useState([]);
const [isloading, setIsloading] = useState(false);
return (
<section className="slit-app--section">
<BrowserRouter>
<Routes>
<Route path="/" element={<Navigate replace to="login" />} />
<Route
excat
path="login"
element={<LoginPage setActiveuser={setActiveuser} />}
/>
<Route
path="homepage"
element={
<>
<NavbarModule />
<BillsModule activeUser={activeUser} />
<ExtraFeaturesModule activeUser={activeUser} />
</>
}
/>
<Route
path="createbill"
element={
<>
<NavbarModule />
<CreateBill />
</>
}
/>
</Routes>
</BrowserRouter>
</section>
);
}
export default App;
function LoginPage({ props, setActiveuser }) {
const usernameInput = useRef(null);
const passwordInput = useRef(null);
function submitClick() {
// extract the input values
const usernameValue = usernameInput.current.value;
const passwordValue = passwordInput.current.value;
// fetch data
const apiUrl = "http://127.0.0.1:8889/api/v1/slitapp";
axios
.get(apiUrl)
.then((response) => {
// slits contain array of 5 objects
const { slits } = response.data.data;
// find if the given username input is in slits data
const foundUser = slits.find((user) => user.username === usernameValue);
if (foundUser?.password === passwordValue) {
setActiveuser(foundUser);
} else {
setActiveuser([]);
}
})
.catch((error) => {
console.error("Error:", error);
});
}
return (
<section className="login_page_section ">
<div className="loginPage">
<h2 className="login_heading">Login</h2>
<form>
<input
className="Login_slitID_input"
placeholder="SLitID"
type="text"
ref={usernameInput}
/>
<input
className="Login_password_input"
placeholder="Password"
type="text"
ref={passwordInput}
/>
<NavLink
to="/homepage"
onClick={submitClick}
className="login_submit_button"
>
submit
</NavLink>
</form>
</div>
</section>
);
}
export default LoginPage;
2
Answers
Instead of using props here , you can keep the loading state inside the
<login/>
Component,}