0-2) React Fetch

terlinko·2023년 8월 4일
0

쇼핑몰 프로젝트

목록 보기
3/6

원래 프론트까지 구현 안 해보려고 했는데,
React Hook 연습 할 겸 대충대충 만들었다.

> npx create-react-app view

React 에서 3000번 포트를 사용할 것이기 때문에, express 의 포트를 바꿔주자.

필자는 3001번 포트로 바꿔주었음.

다시 리액트로 돌아와서..

디자인 되어있는 걸 지우고 난 후에, App.js 에 우리의 코드를 작성해보자.

import { useEffect, useState } from "react"

function UserList(){
  const [List, setList] = useState([]);

  useEffect(()=>{
    const url = 'http://localhost:3001/user';
    const fetchData = async () =>{
      try{
        const res = await fetch(url);
        if(res.ok){
          const data = await res.json();
          setList(data);
        }
      }catch(err){
        console.error(err);
      }
    };

    fetchData();
  },[]);

  return(
    <>
    <h2>User List</h2>
    <ul>
      {List.map((user)=>{
        return(
        <li key={user.seq} className="list_item"><p>{user.seq}.</p>
        <p>username : {user.name}</p>
        <p>Phone : {user.phone}</p>
        </li>
      )
      })}
    </ul>
    </>
  )
  
}

<UserList />는 이제 3001번 포트에서 보내준 유저들의 리스트를 보기 좋게 잘 포장해서 보여주는 컴포넌트이다.

따로 컴포넌트 파일을 나누지 않고 App.js에 작성했다.

사용하려면 이렇게 ..

function App() {
  return (
    <div className="App">
      <UserList />
    </div>
  );
}

export default App;

사실 Hook 사용법 빼고는 별볼일 없는 프로젝트였다.

+수정 ) Express 에서 cors 모듈을 설치하지 않으면 fetch 과정에서 오류가 발생한다.

0개의 댓글