In my react application, I have login page and dashboard. I want to display username, fetched from login page to dashboard using context API.
Following is my App.js code:
import React from 'react';
import {
BrowserRouter as Router,
Route
} from 'react-router-dom';
import Dashboard from './Dashboard';
import Login from './Login'
import {UserContextProvider} from './context/UserContextManagement'
const DashboardPage = () => (<Dashboard />);
const LoginPage = () => (<Login />);
function App() {
return (
<Router>
<UserContextProvider>
<Route path="/login" component={LoginPage} />
<Route path="/dashboard" component={DashboardPage} />
</UserContextProvider>
</Router>
);
}
export default App;
Following is my Login.js Code:
import {UserContext} from '../../context/UserContextManagement'
function Login() {
const {setUsernm}=React.useContext(UserContext);
const handleSubmit = (e) => {
e.preventDefault();
window.location = '/dashboard';
}
return (
<div>
<form>
<input type="text" onChange={e => {setUsernm(e.target.value)}}/>
<input type="text" onChange={e => setPwd(e.target.value)} />
<button type="submit">Sign In </button>
</form>
</div>
);
}
export default Login;
Following is my UserContextManagement:
import React,{useState} from 'react'
export const UserContext = React.createContext();
//Customised Provider
export const UserContextProvider = ({children}) => {
const [usernm, setUsernm] = useState("invalid"); //Due to Usestate, value is resetted
return (
<UserContext.Provider value={{ usernm: usernm, setUsernm: setUsernm }}>
{children}
</UserContext.Provider>
)
}
Issue: I am able to update username by using setUsernm
in login.js file but since both login.js and dashboard.js is route in App.js using same UserContextProvider
. UserContextProvider
is executed again while redirecting from login to dashboard and due to useState
initialization, usernm
is reset to state default i.e. invalid.
How to define useState in such a way that username is not reset to state default value?
We would need to see your login component as well because it seems to be working as intended ?
Maybe your app is reloading so the context is lost ?
To redirect you should use react-router-dom functions.
Your login should ressemble that :
import { useHistory } from 'react-router-dom'
function Login() {
let history = useHistory()
let {setUsername} = useContext(UserContext)
function handleSubmit(e) {
e.preventDefault();
// Do the things you need
history.push('/dashboard')
}
return (
<div>
<form>
<input type="text" onChange={e => {setUsername(e.target.value)}}/>
<input type="password" onChange={e => setPwd(e.target.value)} /> // Use password type
<button type="submit" onClick={(e) => handleSubmit(e)>Sign In </button> // Probably gonna need to attach the function to onClick
</form>
</div>
);
}