1. 리덕스로 폼 상태 관리하기

auth  모듈을 수정해준다.

 

/*
 * <pre>
 * @title auth.js
 * @desc auth 모듈생성 (redux toolkit적용 ), counterSlice api사용
 * </pre>
 *
 * @author yunrap
 * @since 2022.07.17 17:27:11
 * @version 0.1.0
 * @see =================== 변경 내역 ==================
 *   날짜       변경자     내용
 *  2022.07.17.  yunrap  최초생성
 */

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  register: {
    username: "",
    password: "",
    passwordConfirm: "",
  },
  login: {
    username: "",
    password: "",
  },
};

export const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {
    sample_action: (state) => {
      state.action = "auth/SAMPLE_ACTION";
    },
    initialize_form: (state, { payload: form }) => ({
      ...state,
      [form]: initialState(form),
    }),
  },
});

export const { sample_action, initialize_form } = authSlice.actions;

export default authSlice.reducer;

처음에 useEeffect로  처음렌더링후 initailiaze_form 액션생성 함수를 호출해준다.

initailiaze_form을 통해초기값을 우선 설정해준다.

 

 

 

 

2.  LoginForm 화면 구현

그후 useDispatch 와 useSelector 함수를 사용하여 컴포넌트와 리덕스를 연동시킨다.

로그인하는 함수를 구현한다.

 

/*
 * <pre>
 * @title LoginForm.js
 * @desc auth 컨테이너 생성
 * </pre>
 *
 * @author yunrap
 * @since 2022.07.25 22:39:34
 * @version 0.1.0
 * @see =================== 변경 내역 ==================
 *   날짜       변경자     내용
 *  2022.07.25.  yunrap  최초작성
 */

import React, { useEffect } from "react";
import AuthForm from "../../components/auth/AuthForm";
import { change_field, initialize_form } from "../../modules/auth";
import { useDispatch } from "react-redux";

const LoginForm = () => {
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(initialize_form);
  }, [dispatch]);

  //인풋 변경 이벤트 핸들러
  const onChange = (e) => {
    const { value, name } = e.target;
    console.log(value);
    dispatch(
      change_field({
        form: "login",
        key: name,
        value,
      })
    );
  };

  return <AuthForm type="login" onChange={onChange}></AuthForm>;
};

export default LoginForm;

onChange 이벤트핸들러를 달아준다면 

input 의값을 넣었을때 dispatch 함수를 통해서 해당값들을 리덕스에 전역으로 값을 보관할수있다.

+ Recent posts