When I use the app and navigate to the SetContext component, I see the value of auth is correct ("dummy value") and after entering a value in the edit field and pressing the button I see the setAuth method trigger in the App component and then I also see the auth changes in the useEffect method of the App component (I just put that in to see if it registered the update). That would be fantastic except that then navigating to any page the value of auth reverts to the original value ("dummy value") and I can't determine why.
Here are my versions of the React libs in use:
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-router": "^6.3.0",
"react-router-dom": "^6.3.0",
Here is my index.js (it is purely boilerplate but I'll post just to prove it):
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: <edited per stack overflow editor requirements>;
Here is my App.js:
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import './App.css';
import { AuthProvider } from './components/AuthContext';
import Navbar from './components/Navbar';
import Home from './components/Home';
import About from './components/About';
import SetContext from './components/SetContext';
function App() {
const [auth, setAuth] = React.useState("dummy value");
React.useEffect(() => {
console.log("auth updated to: "+auth);
}, [auth]);
const changeAuth = (value) => {
setAuth(value);
}
return (
<>
<AuthProvider value={auth}>
<Router>
<Navbar />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/home" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/setcontext" element={<SetContext setAuth={changeAuth} />} />
</Routes>
</Router>
<footer>This is the footer</footer>
</AuthProvider>
</>
);
}
export default App;
And finally here is my SetContext.js:
import React from 'react';
import AuthContext from './AuthContext';
const SetContext = ( { setAuth } ) => {
const auth = React.useContext(AuthContext);
const changeHandler = (event) => {
const value = document.getElementById("newContext").value;
setAuth(value);
}
return (
<>
<div>This is the SetContext Component The auth context value is {auth}</div>
<div><input id="newContext"></input></div>
<div><button onClick={changeHandler}>Set Context</button></div>
</>
);
}
export default SetContext;