[React + TS] 회원가입 구현하기

개발냥이·2025년 4월 22일

데브코스

목록 보기
44/75
post-thumbnail

백엔드 파트 시간에 작업했던 북스토어 내용을 드디어 프론트엔드와 연동을 시작했다!!

카테고리부터 가져오기 시작했으나 회원가입 / 로그인이 기본인 거 같아 해당 내용을 작성해보고자 한다.

과정

  1. axios 다운 및 HTTP client 설정
  2. api 호출
  3. 페이지 구현

1. axios 다운 및 설정

axios란 ??

HTTP 요청을 처리하기 위한 라이브러리이다.

사용 이유

제일 큰 장점은 간편하게 코드를 작성할 수 있다는 점이다!!

[사용전]

const fetchData = async () => {
  try {
    const response = await fetch('http://');
    
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error fetching data:', error);
  }
};

fetchData();

[사용 후]

import axios from 'axios';

const fetchData = async () => {
  try {
    const response = await axios.get('https://');
    console.log(response.data);
  } catch (error) {
    console.error('Error fetching data:', error);
  }
};

fetchData();

axios를 사용하기 전에는 받아온 데이터를 JSON으로 변환해서
(await response.json()) 사용해야 했으나

axios는 자동으로 JSON 변환 해주기 때문에 변환 과정없이
(response.data) 바로 사용이 가능하기 때문에 간편하다!!

axios 설치

  • npm i axios

HTTP 클라이언트 설정하기

api 폴더를 만든 후 http.ts라는 이름의 파일을 생성 하여
HTTP 클라이언트를 설정했다.
HTTP 클라이언트를 설정하는 이유는 API 호출 시 이 파일만 호출하면 사용할 수 있게 되어 HTTP 요청을 관리하기 용이하다

코드 보기
import axios, {AxiosRequestConfig} from 'axios';

const BASE_URL = 'http://localhost:7777';
const DEFAULT_TIMEOUT = 30000;

//  HTTP client 설정
export const createClient = (consfig?: AxiosRequestConfig) => {
  const axiosInstance = axios.create({
    baseURL: BASE_URL,
    timeout: DEFAULT_TIMEOUT,
    headers: {
      'content-type': 'application/json',
    },
    withCredentials: true,
    ...consfig,
  });

  axiosInstance.interceptors.response.use(
    res => {
      return res;
    },
    err => {
      return Promise.reject(err);
    },
  );

  return axiosInstance;
};

export const httpClient = createClient();

2. api 호출

이제 회원가입 API인 post 메서드를 호출해서 사용하면 된다.
위의 http.ts와 같은 경로에 auth.api.ts라는 이름의 파일을 사용했다

import {httpClient} from './http';

export interface SignupProps {
  email: string;
  password: string;
}

export const signup = async (userData: SignupProps) => {
  const res = await httpClient.post('/users/joinup', userData);

  return res.data;
};

앞서 다 설정을 해뒀기에 여기서는 편하게
메서드 (post) , 경로 (/users/joinup) , body값 (userData)만 사용해서 회원가입 기능을 구현할 수 있다 ㅎㅎ


3. 페이지 구현

const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const nav = useNavigate();

const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
      e.preventDefault();
     };

  const onSubmit = (data: SignupProps) => {
    signup(data).then(res => {
      nav('/login');
    });
  };

        <form onSubmit={handleSubmit(onSubmit)}>
          <fieldset>
            <InputText
              placeholder="이메일"
              inputType="email"
              value={email}
              onChange={e => setEmail(e.target.value)}
            />
          </fieldset>
          <fieldset>
            <InputText
              placeholder="비밀번호"
              inputType="password"
              value={password}
              onChange={e => setPassword(e.target.value)}
           
            />
           
          </fieldset>
          <fieldset>
            <Button type="submit" size="small" scheme="primary">
              회원가입
            </Button>

주요 코드만 보면 다음과 같다.
사용자가 이메일과 비밀번호를 입력하면
form의 onSubmit 이벤트 핸들러로 onSubmit을 호출하고
onSubmit은 앞서 작성했던 auth.api.ts 파일에 userData 이곳에 정보를 담아서 보내준다.


🤔후기

사실 회원가입 과정에서 무언가를 배웠다기 보단
커스텀 훅과 axios의 장점에 대해 깨닫고 배우게 된 거 같다.
지금까지 커스텀 훅은 정말 사용하지 않았는데
재사용성이 너무 좋아서 한번 잘 만들어두면 프로젝트 시 엄청 편할 거 같다
또한 axios는 그냥 사용만 하고 있었는데 이번 계기로 왜 사용하고
왜 기본 api 통신보다 간편한 건지 확실히 알게 되었다 ㅎ

profile
웹 개발자가 되고픈

0개의 댓글