728x90
반응형

 

SignupComponent 부분에 더 입력해야 될 값들을 추가해서 화면구성을 하자.

 

SignupComponent.tsx

import type { NextPage } from 'next'
import { UserState } from "../../store/interfaces/"
import { useDispatch, useSelector } from "react-redux";
import { actionTypesUser } from "../../store/interfaces/user/userAct.interfaces"
import { RootStateInterface } from "../../store/interfaces/RootState";

interface Props {
    userChangeHandler : (event : any) => void;
    userState : UserState;
}

const Signup:NextPage<Props> = ({userChangeHandler,userState}) => {
    const dispatch = useDispatch();
    const submitHandler = (event : any) => {
        event.preventDefault()
    }
    return (
        <div className="signup">
            <form onSubmit={submitHandler}>
                <div>
                    <input 
                        name="id"
                        type="text"
                        placeholder="Enter ID"
                        onChange={userChangeHandler} />
                    <button>
                    중복확인     
                    </button>
                </div>
                <div>
                    <input 
                        name="pw"
                        type="password"
                        placeholder="Enter PW"
                        onChange={userChangeHandler} />
                </div>
                <div>
                    <input 
                        name="pw2"
                        type="password"
                        placeholder="Verify password"/>
                </div>
                <div>
                    <input 
                        name="email"
                        type="email"
                        placeholder="Enter Email"
                        onChange={userChangeHandler} />
                    <button>
                    보내기    
                    </button>
                </div>
                <div>
                    <input 
                        name="address"
                        type="text"
                        placeholder="Enter Address"
                        onChange={userChangeHandler} />
                    <button>
                    주소검색    
                    </button>
                </div>
                <div className="signbutton">
                    <button
                        type="submit">
                    Signup       
                    </button>
                </div>
            </form>
        </div>
        )
}

export default Signup

 

 나중에 중복확인이 완료되고 id 입력칸을 비활성화로 만들어주기 위해 state를 만들어준다.

    //idDuple
    const [idDupleOK,setIdDupleOK] = useState<boolean>(false)

 

 

화면 부분도 바꿔준다.

<div>
    <input 
        name="id"
        type="text"
        placeholder="Enter ID"
        onChange={userChangeHandler}
        disabled={idDupleOK} />
    <button
    	type="button"
        onClick={IdDuplicate}
        disabled={userState.idDuple}
        >
    중복확인
    </button>
</div>

 

 

 화면으로 확인해보자.

 

 

참고로 기능위주로 구현하고 CSS는 나중에 다룰것이다. ( div에 className을 하나씩 추가한 이유 )

 

로그를 확인해보면 userState 값이 정상적으로 바뀌는것을 확인할 수 있다.

axios 모듈이 없으면 npm i axios 로 설치하면 된다.

id를 파라미터로 받아 백엔드에 GET 메소드로 데이터를 요청해 반환값을 전달하는 userIdDuplicate 함수를 작성했다.

 

이제 userAct.interfaceuser_reducer부분에 ID중복확인 부분을 추가해준다.

 

user.interface.ts

export enum actionTypesUser {
    USER_INIT = "USER_INIT", // state 초기화
    USER_STATE = "USER_STATE", // userState 변경
    USER_INFO = "USER_INFO",  // userInfo 변경 
    USER_ID_DUPLICATE = "USER_ID_DUPLICATE" // ID 중복 검사
}

export type ActionsUser = UserInit | UserState | UserInfo | UserIdDuplicate

export interface UserInit {
    type : actionTypesUser.USER_INIT;
    data : any;
}

export interface UserState {
    type : actionTypesUser.USER_STATE;
    data : any;
}

export interface UserInfo {
    type : actionTypesUser.USER_INFO;
    data : any;
}

export interface UserIdDuplicate {
    type : actionTypesUser.USER_ID_DUPLICATE;
    payload: any;
}

 

user_reducer.ts

        case actionTypesUser.USER_ID_DUPLICATE:
            return {
                ...state, data : action.payload
            }

 

ID중복확인을 위한 함수를 작성하기 전에 우리가 USER_STATE, USER_INFO 액트를 쓸 땐 백엔드(NestJS)와의 통신이 없어도 상관없었지만 ID 중복확인을 위한 과정에는 백엔드(NestJS)와의 통신이 필요하다.

 

때문에 dispatch에 사용될 Action을 정의할 것이다.

store 밑에 user_action.ts 파일을 생성한다.

/store/user_action.ts

import Axios from 'axios'
import { actionTypesUser } from '../interfaces'

export async function userIdDuplicate (id : string) {
    const request = Axios.get('/api/user/'+id)
    .then(response => response.data)
    
    return {
        type : actionTypesUser.USER_ID_DUPLICATE,
        payload: request
    }
}

 

이제 컴포넌트에서 dispatch로 axios의 결과값에 따른 로직을 만들어준다.

SignupComponent.tsx

import {userIdDuplicate} from '../../store/actions/user_action'

    (...)
    
    //idDuple
    const [idDupleOK,setIdDupleOK] = useState<boolean>(false)
    }
    const IdDuplicate = () => {
        if(userState.userInfo.id !=='') { // 입력된 값이 존재할 경우
            dispatch(userIdDuplicate(userState.userInfo.id)).then((req : any)=> {
                if(!req.payload.result) { // 아이디가 이미 존재할 때
                    alert('해당 아이디가 이미 존재합니다.');
                }else {
                    alert('중복된 아이디가 없습니다.');
                    dispatch({type : actionTypesUser.USER_STATE, data: ['idDuple',true]});
                    setIdDupleOK(true);
                }
            })
        }
    }
    
    (...)
    
    <input 
      name="id"
      type="text"
      placeholder="Enter ID"
      onChange={userChangeHandler}
      disabled={idDupleOK} />
    <button
      type="button"
      onClick={IdDuplicate}
      disabled={userState.idDuple}
    >
    중복확인     
    </button>
    
    (...)

 

  1. 만들어두었던 action을 가져온다.
  2. 버튼을 클릭할 경우 동작될 함수를 선언한다.
  3. 함수에선 dispatchdata에 입력한 ID를 전달한다.
  4. 반환값에 따라 조건문을 써준다. 만약 중복된 아이디가 없을 경우 UserStateidDuple값을 바꿔준다.

 

여기까지 중복확인 버튼을 눌렀을 때 dispatch로 백엔드에 데이터를 요청해서 원하는 값을 받아오고,

받아온 값에 따라 어떻게 처리할지 조건문으로 써주었다. 

 

다음 포스트에서는 백엔드(NestJS)를 구성해보겠다.

 

 

728x90
반응형

+ Recent posts