I have a react app that uses express session. The standard session and cookies work as expected but I am trying to add a custom field outside of a req context as below.
import session from 'express-session';
export default ({ children }) => {
console.log("session.darkState at top ", session.darkState);//check whats stored when refreshed
const [darkState, setDarkState] = useState(session.darkState?session.darkState:false);
function giveMeTheme(darkStateFromAppBar) {
setDarkState(darkStateFromAppBar);
session.darkState = darkState;//store in session
console.log(session.darkState);
}
I am not able to use req context so I am simply using session.....
session.darkState
goes back to undefined when user navigates to another page or refreshes.
How to store a field for the length of the session?
I use mongo store and when user logs in, I am saving all standard fields such as resave, saveUninitialized in mongodb.
I could not find a solution to add custom cookie with express session so ended up using react-cookie
import { useCookies } from 'react-cookie';
import NameForm from './NameForm';
function App() {
const [cookies, setCookie] = useCookies(['name']);
function onChange(newName) {
setCookie('name', newName, { path: '/' });
}
return (
<div>
<NameForm name={cookies.name} onChange={onChange} />
{cookies.name && <h1>Hello {cookies.name}!</h1>}
</div>
);
}