Skip to content

Instantly share code, notes, and snippets.

@conste11ations
Created December 1, 2021 05:24
Show Gist options
  • Save conste11ations/ef0d5a2a429e3b7a9e1f5a7868bd51ab to your computer and use it in GitHub Desktop.
Save conste11ations/ef0d5a2a429e3b7a9e1f5a7868bd51ab to your computer and use it in GitHub Desktop.
Auth context SSR
import { createContext } from "react";
const authContext = createContext({
authenticated: false,
setAuthenticated: (auth) => {}
});
export default authContext;
<body>
<div id="container"></div>
</body>
import ReactDOM from "react-dom";
import React, { useEffect, useState } from "react";
import authContext from "./authContext";
import Login from "./Login";
const App = () => {
const [authenticated, setAuthenticated] = useState(false);
useEffect(() => {
setAuthenticated(localStorage.getItem("loggedIn") === "true");
}, []);
return (
<authContext.Provider value={{ authenticated, setAuthenticated }}>
<div> user is {`${authenticated ? "" : "not"} authenticated`} </div>
<Login />
</authContext.Provider>
);
};
ReactDOM.render(<App />, document.getElementById("container"));
import React, { useContext } from "react";
import authContext from "./authContext";
export default () => {
const { setAuthenticated } = useContext(authContext);
const handleLogin = () => {
setAuthenticated(true);
localStorage.setItem("loggedIn", true);
};
const handleLogout = () => {
setAuthenticated(false);
localStorage.setItem("loggedIn", false);
};
return (
<React.Fragment>
<button onClick={handleLogin}>login</button>
<button onClick={handleLogout}>logout</button>
</React.Fragment>
);
};
{
"name": "react-playground",
"version": "1.0.0",
"description": "",
"keywords": [],
"main": "index.js",
"dependencies": {
"react": "17.0.1",
"react-dom": "17.0.1",
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment