Skip to content

Commit 1d67938

Browse files
committed
Merge branch 'master' of github.com:alstn2468/DoIt_Typescript_Programming
Matching current branch
2 parents a28ecc5 + 60b5efc commit 1d67938

File tree

9 files changed

+136
-3
lines changed

9 files changed

+136
-3
lines changed

.DS_Store

0 Bytes
Binary file not shown.

Summary/ms/.DS_Store

0 Bytes
Binary file not shown.

Summary/ms/Chapter_12/.DS_Store

0 Bytes
Binary file not shown.

Summary/ms/Chapter_12/12.md

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1947,8 +1947,117 @@ const App: React.FC = () => {
19471947
19481948
### API 서버에서 실제 데이터 가져오기
19491949
1950+
[12-3](#12-3-익스프레스로-api-서버-만들기)에서 개발한 API 서버를 동작시킨 후 `React` 프로젝트와 연결을 진행한다.<br/>
1951+
1952+
```shell
1953+
> npm start
1954+
```
1955+
1956+
위의 `start` 명령어를 사용해 API 서버를 동작시킨다.<br/>
1957+
그 후 `React` 프로젝트의 `src`폴더에 `IUser.ts`파일으 생성한 후 작성한다.<br/>
1958+
1959+
- `IUser.ts`
1960+
1961+
```typescript
1962+
export interface IUser {
1963+
_id: string;
1964+
name: string;
1965+
email: string;
1966+
sentence: string;
1967+
profession: string;
1968+
birthday: Date;
1969+
}
1970+
```
1971+
1972+
그 후 `src`폴더에 2차 고차 함수 형태의 `getDataPromise` 함수를 작성한다.<br/>
1973+
1974+
- `getDataPromise.ts`
1975+
1976+
```typescript
1977+
import { IUser } from "./IUser";
1978+
1979+
type GetDataPromiseCallback = (a: IUser[]) => void;
1980+
1981+
export const getDataPromise = (fn: GetDataPromiseCallback) => (
1982+
skip: number,
1983+
limit: number
1984+
) =>
1985+
fetch(`http://localhost:4000/users/${skip}/${limit}`)
1986+
.then((res) => res.json())
1987+
.then(fn);
1988+
```
1989+
1990+
마지막으로 `App.tsx` 파일을 아래와 같이 수정한 후 저장해 반영한다.<br/>
1991+
1992+
- `App.tsx`
1993+
1994+
```tsx
1995+
import React from "react";
1996+
import { IUser } from "./IUser";
1997+
import { getDataPromise } from "./getDataPromise";
1998+
1999+
const App: React.FC = () => {
2000+
getDataPromise((users: IUser[]) => console.log("users", users))(0, 1);
2001+
2002+
return <div className="App">Please open console window!</div>;
2003+
};
2004+
2005+
export default App;
2006+
```
2007+
2008+
브라우저를 열어 개발자 도구의 콘솔을 확인하면 아래와 같은 결과를 볼 수 있다.<br/>
2009+
2010+
<img src="./images/18.png" width="550" height="auto">
2011+
2012+
위와 같이 API 서버에서 실제 데이터를 가져온 것을 확인할 수 있다.<br/>
2013+
19502014
### useState 함수 사용하기
19512015
2016+
지금까지 작성한 `App` 컴포넌트에는 한 가지 문제점이 있다.<br/>
2017+
2018+
```tsx
2019+
const App: React.FC = () => {
2020+
getDataPromise((users: IUser[]) => console.log("users", users))(0, 1);
2021+
2022+
return <div className="App">Please open console window!</div>;
2023+
};
2024+
```
2025+
2026+
서버에서 가져온 `users` 값을 컴포넌트에서 사용할 수 없고 콜백 함수에서만 사용할 수 있다.<br/>
2027+
`React`는 이러한 문제를 해결할 수 있도록 `useState`라는 컴포넌트 상태관리 함수를 제공한다.<br/>
2028+
2029+
```tsx
2030+
import React, { useState } from "react";
2031+
```
2032+
2033+
`useState` 함수는 배열에 **비구조화 할당문**을 사용해 아래와 같이 사용할 수 있다.<br/>
2034+
2035+
```typescript
2036+
const [users, setUsers] = useState<IUser[]>([]);
2037+
```
2038+
2039+
`useState`의 반환값인 배열의 첫번째 값은 **상태**이며 두번째 값은 **상태를 변경하는 함수**다.<br/>
2040+
`useState`를 사용해 서버에서 가져온 `IUser` 타입 데이터를 아래와 같이 저장할 수 있다.<br/>
2041+
2042+
- `App.tsx`
2043+
2044+
```tsx
2045+
const App: React.FC = () => {
2046+
const [users, setUsers] = useState<IUser[]>([]);
2047+
getDataPromise((receivedUsers: IUser[]) =>
2048+
setUsers([...users, ...receivedUsers])
2049+
)(0, 1);
2050+
2051+
return <div className="App">{JSON.stringify(users)}</div>;
2052+
};
2053+
```
2054+
2055+
작성한 코드를 저장한 후 브라우저를 보면 아래와 같이 실제 데이터가 표시되는 것을 볼 수 있다.<br/>
2056+
2057+
<img src="./images/19.png" width="500" height="auto">
2058+
2059+
가져온 데이터를 `users` 상태에 저장한 후 문자열 형태로 변한해 화면에 보이게 된다.<br/>
2060+
19522061
### useEffect 함수 사용하기
19532062
19542063
### 서버에서 데이터 계속 가져오기
Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,14 @@
1-
import React from "react";
1+
import React, { useState } from "react";
2+
import { IUser } from "./IUser";
3+
import { getDataPromise } from "./getDataPromise";
24

35
const App: React.FC = () => {
4-
const user = { name: "Jack", age: 32 };
6+
const [users, setUsers] = useState<IUser[]>([]);
7+
getDataPromise((receivedUsers: IUser[]) =>
8+
setUsers([...users, ...receivedUsers])
9+
)(0, 1);
510

6-
return <div className="App">{JSON.stringify(user)}</div>;
11+
return <div className="App">{JSON.stringify(users)}</div>;
712
};
813

914
export default App;
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
export interface IUser {
2+
_id: string;
3+
name: string;
4+
email: string;
5+
sentence: string;
6+
profession: string;
7+
birthday: Date;
8+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { IUser } from "./IUser";
2+
3+
type GetDataPromiseCallback = (a: IUser[]) => void;
4+
5+
export const getDataPromise = (fn: GetDataPromiseCallback) => (
6+
skip: number,
7+
limit: number
8+
) =>
9+
fetch(`http://localhost:4000/users/${skip}/${limit}`)
10+
.then((res) => res.json())
11+
.then(fn);
83.6 KB
Loading
285 KB
Loading

0 commit comments

Comments
 (0)