Skip to content

Commit 75beb68

Browse files
committed
useContext x useState
1 parent 05bdbca commit 75beb68

File tree

2 files changed

+17
-7
lines changed

2 files changed

+17
-7
lines changed

src/App.js

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
1-
import React from 'react';
1+
import React, { useState } from 'react';
22
import './App.css';
33
import LoginArea from './LoginArea';
44

5-
const fakeUser = { username: 'nice789', fullname: 'เต้า หมิงซื่อ' };
6-
75
const AuthContext = React.createContext();
86

97
function App() {
8+
const [auth, setAuth] = useState(null);
109
return (
11-
<AuthContext.Provider value={fakeUser}>
10+
<AuthContext.Provider value={{ auth, setAuth }}>
1211
<section className="app-section">
1312
<div className="app-container">
1413
<LoginArea />

src/LoginBox.js

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,33 @@
11
import { useContext } from "react";
22
import { AuthContext } from "./App";
33

4+
const fakeUser = { username: 'nice789', fullname: 'เต้า หมิงซื่อ' };
5+
46
function LoginBox() {
5-
const auth = useContext(AuthContext);
7+
const { auth, setAuth } = useContext(AuthContext);
8+
9+
function loginSubmit(event) {
10+
event.preventDefault();
11+
setAuth(fakeUser);
12+
}
13+
14+
function logoutSubmit() {
15+
setAuth(null);
16+
}
617

718
if (!!auth) {
819
return (
920
<div>
1021
<h3>เข้าสู่ระบบแล้วจ้า</h3>
1122
<p>Auth username = {auth.username}</p>
1223
<p>Auth fullname = {auth.fullname}</p>
13-
<p><button>Log out</button></p>
24+
<p><button onClick={logoutSubmit}>Log out</button></p>
1425
</div>
1526
);
1627
}
1728

1829
return (
19-
<form onSubmit>
30+
<form onSubmit={loginSubmit}>
2031
<h3>โปรดเข้าสู่ระบบ</h3>
2132
<p><input type="text" placeholder="Username" /></p>
2233
<p><input type="password" placeholder="Password" /></p>

0 commit comments

Comments
 (0)