-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #49 from su-its/feat/add-login-context
Feat/add login context
- Loading branch information
Showing
3 changed files
with
58 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
# 状態管理 | ||
## ログイン状態 | ||
|
||
- ログインしているかどうか判断したいとき | ||
|
||
```tsx | ||
"use client"; | ||
import { useUser } from "@/state"; | ||
|
||
export function LoginStatus() { | ||
const user = useUser() | ||
|
||
return <div>User is{user ? " " : " not "}logged in!</div> | ||
} | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
"use client"; | ||
import { ReactNode, createContext, useContext } from "react"; | ||
|
||
// TODO: あとで直す。適当な型であることを明示するためにあえてへんな名前にしてる | ||
type UserType001 = { | ||
student_number: string; | ||
handle_name: string; | ||
}; | ||
|
||
export const LoginContext = createContext<UserType001 | undefined>(undefined); | ||
|
||
export function useUser() { | ||
return useContext(LoginContext); | ||
} | ||
|
||
type LoginProviderProps = { | ||
children: ReactNode; | ||
user?: UserType001; | ||
}; | ||
|
||
/** | ||
* Server Component で Context が使えないのでその children の Client Component で `useUser()` できない。 | ||
* これをできるようにするための Client Component。`LoginContext.Provider` を挟むだけ。 | ||
* - https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns#using-context-providers | ||
* - https://future-architect.github.io/articles/20231214a/ | ||
*/ | ||
export function LoginProvider({ children, user }: LoginProviderProps) { | ||
return <LoginContext.Provider value={user}>{children}</LoginContext.Provider>; | ||
} |