Global

Methods

ContextProviderState(props) → {JSX.Element}

Description:
  • 이 컴포넌트는 React의 Context API를 사용하여 공유 상태를 제공합니다. 여러 상태 변수와 해당 상태 변경 함수를 관리하며, 이를 하위 컴포넌트에서 사용할 수 있도록 합니다.
Version:
  • 1.0.0
Author:
See:
To Do:
  • ContextAPI 대신 Recoil을 사용해 비교해본다.
Properties:
Name Type Description
isState string 현재 상태 값 / default: `oldValue`
isNum number 숫자 상태 값 (사용예시를 위한 값) / default: `1`
isModalType string 모달의 타입 / default: `빈 문자열`
isModalState boolean 모달의 표시 여부 / default: `false`
isWorkSheetId undefined | number 워크시트 ID / default: `undefined`
isSelectedId undefined | number 현재 선택된 항목의 ID / default: `undefined`
isUser undefined | Object 사용자 데이터 / default: `undefined`
isUserName undefined | string 사용자 이름 / default: `undefined`
Example
// useGlobalState에서의 사용 예시입니다.
const context = useContext(StateContext);
Parameters:
Name Type Description
props Object 컴포넌트에 전달되는 props
Properties
Name Type Description
children ReactNode Provider로 래핑할 React 엘리먼트 또는 컴포넌트
Returns:
`ContextProviderState`는 자식 컴포넌트(App)를 Context Provider로 래핑하며, 상태 값과 변경 함수들을 제공합니다.
Type
JSX.Element
Description:
  • 이 컴포넌트는 전역 상태를 관리하며 모달 창을 열고 닫는 기능을 제공한다. 사용자가 클릭하여 모달을 닫거나 특정 `ModalType`을 렌더링할 수 있다. `isOpen` 상태를 기반으로 모달을 렌더링하며, 모달이 열릴 때 스크롤 비활성화 기능을 제공한다.
Version:
  • 1.0.0
Author:
See:
Example
// 기본 사용법
import Modal from './Modal';

const App = () => {
  const [isOpen, setIsOpen] = useState(false);

  const toggleModal = () => setIsOpen(!isOpen);

  return (
    <div>
      <button onClick={toggleModal}>Open Modal</button>
      <Modal
        isOpen={isOpen}
        ModalType={MyModalComponent}
        postData={{ data: { content: { holidayPayMessage: '내용' } } }}  // post 되는 데이터가 있을 경우 사용
        postContent="모달 내용"  // ModalType 중에 postContent가 필요한 경우 상요 `ModalResult.components.tsx`가 대표적이다.
      />
    </div>
  );
};
Parameters:
Name Type Description
props Object Modal 컴포넌트의 Props, Modal의 Components는 Global/Components/ModalType에서 확인 가능하다.
Properties
Name Type Attributes Description
isOpen boolean 모달이 열렸는지 여부를 나타내는 상태.
ModalType React.ElementType 렌더링할 모달의 타입(컴포넌트).
postData Object <optional>
모달 내부에서 사용될 데이터.
postContent string <optional>
모달의 텍스트 콘텐츠.
Returns:
- 모달 컴포넌트를 반환하며, `isOpen`이 `false`인 경우 `null`을 반환.
Type
JSX.Element | null

ModalResult(props) → {JSX.Element}

Description:
  • 이 컴포넌트는 결과지 이름을 입력받고 저장하기 버튼 클릭 시 POST 요청을 통해 데이터를 서버로 전송한다. 데이터 전송 후 성공적으로 처리되면 부모 컴포넌트의 상태를 변경하여 모달 상태를 업데이트한다.
    주의 사항
    - `postData`와 `postContent`는 필수 props이며 올바르게 제공되어야 한다.
    - `postData`의 필드는 명시된 타입에 맞아야 한다.
Version:
  • 1.0.0
Author:
See:
Example
<ModalResult
  postData={{
    total_pay: 5000000,
    extra_pay: true,
    week_pay: true,
    night_pay: false,
    overtime_pay: true,
    holiday_pay: false,
  }}
  postContent="근로 결과지에 관한 내용"
/>
Parameters:
Name Type Description
props Object 컴포넌트에 전달되는 props
Properties
Name Type Description
postData Object 서버에 전송할 데이터 객체
Properties
Name Type Description
total_pay number 총 지급액
extra_pay boolean 추가 지급 여부
week_pay boolean 주휴수당 여부
night_pay boolean 야간수당 여부
overtime_pay boolean 초과근무수당 여부
holiday_pay boolean 휴일수당 여부
postContent string 전송할 내용의 텍스트
Returns:
결과지 모달 UI를 반환한다.
Type
JSX.Element

VmwrResult(props) → {JSX.Element}

Description:
  • API로부터 받은 근로 결과 데이터를 렌더링하는 VmwrResult 컴포넌트입니다.
Version:
  • 1.0.0
Author:
See:
Example
return <VmwrResult data={data} />;
Parameters:
Name Type Description
props Object 컴포넌트에 전달되는 props
Properties
Name Type Description
data Array 근로 결과 데이터 배열
Properties
Name Type Description
data Object 근로 결과 데이터 객체
status number HTTP 상태 코드 (예: 200, 404)
data.nickname string 근로자 닉네임
data.title string 근로지 이름
data.content string 결과지 설명
data.extraPay boolean 가산수당 여부
data.weekPay boolean 주휴수당 여부
data.nightPay boolean 야간 근로 수당 여부
data.overtimePay boolean 연장 근로 수당 여부
data.holidayPay boolean 휴일 근로 수당 여부
message string 결과 메시지
Returns:
VmwrResult 컴포넌트를 반환합니다.
Type
JSX.Element

fetchAPI(baseURLopt) → {AxiosInstance}

Description:
  • 이 함수는 기본 API URL을 설정하고, timeout 및 기본 header와 같은 공통 설정이 포함된 Axios instance를 생성하여 반환한다. `.env` 파일에서 환경 변수 `REACT_APP_API_URL` 값을 가져와 기본 URL로 설정하며 별도로 전달된 `baseURL` 값을 사용할 수도 있다.
    참고로 하단 property는 axios.create의 속성이므로 착오 없이 fetch.instance.js 함수와는 무관함을 인지해야 한다.
Version:
  • 1.0.0
Author:
See:
To Do:
  • Promise.all을 사용해서 직렬 Fetch를 병렬 Fetch로 변환해본다.
Properties:
Name Type Description
baseURL string (해당 속성은 axios.create의 속성입니다.) API 요청의 기본 URL
timeout number (해당 속성은 axios.create의 속성입니다.) 요청 timeout을 5000ms(5초)로 설정
headers Object (해당 속성은 axios.create의 속성입니다.) 기본 요청 headers를 설정, 기본적으로 `Content-Type: application/json`을 포함한다.
Example
// 기본 URL을 사용하여 Axios 인스턴스 생성
// useFetchAPI 참조
const api = fetchAPI();

// 사용자 지정 baseURL을 사용하여 Axios 인스턴스 생성
const customAPI = fetchAPI('https://custom-api.example.com');

// API 요청 예시
api.get('/endpoint')
  .then(response => {
    console.log('Response data:', response.data);
  })
  .catch(error => {
    console.error('Error:', error);
  });
Parameters:
Name Type Attributes Default Description
baseURL string <optional>
REACT_APP_API_URL API 요청의 기본 URL. 설정하지 않으면 환경 변수 `REACT_APP_API_URL`을 기본값으로 사용
Returns:
설정된 Axios 인스턴스를 반환한다. 이를 통해 API 요청을 손쉽게 처리할 수 있다.
Type
AxiosInstance

generateResultContent(isData, isUserName) → {Object}

Description:
  • 이 함수는 근로 결과지에 대한 api 데이터를 받아 근로 결과지 화면의 글씨 데이터를 생성합니다.
    근로 결과지에 대한 데이터는 사용자 이름, 가산 수당 발생 여부, 주휴 수당 발생 여부, 야간 수당 발생 여부, 연장 근로 수당 발생 여부, 휴일 근로 수당 발생 여부, 4대보험 및 소득세 적용 여부, 총 급여입니다. 각 데이터의 true or false/시간/금액에 따라 해당하는 문구를 생성합니다.
    자세한 예시는 아래를 참고해주세요.
Version:
  • 1.0.0
Author:
See:
Example
// 이 부분은 원래 받아온 api 데이터를 사용하는 부분이지만, 테스트를 위해 데이터를 직접 입력하였습니다.
const data = {
 over_five: true,
 week_pay: false,
 week_work: 14,
 night_pay: false,
 night_work: 0,
 overtime_pay: false,
 overtime_work: 0,
 holiday_pay: false,
 holiday_work: 0,
 major_insurance: true,
 income_tax: true,
 total_pay: 800000,
};
const userName = '코카콜라';
const result = generateResultContent(data, userName);
console.log(result);

// 위 데이터에 대한 반환값(result 값)은 다음과 같습니다.
// '상시 5인 이상 사업장에서 근무하시므로 추가적인 가산 수당이 발생합니다.'
// '주 근로 시간이 14시간으로 주휴수당이 발생하지 않습니다.'
// '한 주 동안 야간 근로시간이 0시간이므로 야간근로수당 0원이 발생합니다.'
// '한 주 동안 연장 근로시간이 0시간이므로 연장근로수당 0원이 발생합니다.'
// '취업 규칙 에서 정한 약정 휴일에 0시간 근무하므로 휴일근로수당 0원이 발생합니다.'
// '4대보험 9.32% 가 적용됩니다.'
// '소득세 3.3%가 적용됩니다.'
// '따라서, 코카콜라 님의 월급은 800,000 원 입니다.'
Parameters:
Name Type Description
isData Object api 데이터로 받아온 결과 데이터 객체입니다. 객체 내부에는 가산 수당 발생 여부, 주휴 수당 발생 여부, 야간 수당 발생 여부, 연장 근로 수당 발생 여부, 휴일 근로 수당 발생 여부, 4대보험 및 소득세 적용 여부, 총 급여가 있습니다.
isUserName string 근로 결과지 생성에 필요한 사용자 이름을 문자열로 받아옵니다.
Returns:
결과 화면의 글씨 데이터를 반환합니다.
Type
Object

modalStateController(isModalState, setModalState)

Description:
  • 모달 상태를 반전시키는 함수이다. 해당 함수를 문서화 한 이유는 Modal Component의 props로 존재하는 isOpen을 Component를 사용할 때 지속적으로 상기시키기 위해서 였다. 이 함수는 React의 `useState`를 통해 관리되는 상태 값을 받아 해당 값을 반전(`true` ↔ `false`)시킨다. 특정 컴포넌트의 모달 상태를 제어하기 위해 사용된니다.
    주의 사항
    - 이 함수는 상태와 상태 변경 함수를 직접 받아야 동작한다.
    - 상태와 상태 변경 함수(`useState`)는 해당 컴포넌트 혹은 부모로부터 전달되어야 한다.
    - 자식 컴포넌트가 부모 컴포넌트의 상태를 직접 제어하려면 부모로부터 상태 변경 함수를 `props`로 전달받아야 한다.
Version:
  • 1.0.0
Author:
See:
Examples
//사용 예시
const [isModalOpen, setModalOpen] = useState(false);

// 상태를 반전시키기
modalStateController(isModalOpen, setModalOpen);
// 부모 상태를 자식에서 제어하는 예시
const ParentComponent = () => {
  const [isModalOpen, setModalOpen] = useState(false);
  return <ChildComponent isModalState={isModalOpen} setModalState={setModalOpen} />;
};
Parameters:
Name Type Description
isModalState boolean 현재 모달의 열림/닫힘 상태 (`true`는 열림, `false`는 닫힘).
setModalState function `useState`로 생성된 상태 변경 함수. 모달 상태를 업데이트한다.

useFetchAPI(initialUrl, methodopt, requestDataopt) → {Object}

Description:
  • <해당 커스텀 훅(Hook)은 `fetch.instance.js`를 기반으로 동작하고 있다. 따라서 해당 Axios instance를 모른다면 `fetch.instance.js`를 보고 오시는 것을 추천 합니다.> useFetchAPI는 4가지 상태를 관리하고 반환한다. 차례대로 `isLoading`, `isUrl`, `isData`, `isError`와 같다. useFetchAPI는 현재 fetchData 함수는 단일 요청만 처리하도록 작성되어 있다. 따라서 한 번 호출할 때 하나의 요청만 수행하며 내부에서 병렬로 여러 요청을 처리하는 로직이 포함되어 있지 않다. 그래서 useFetchAPI를 다중으로 사용할 때는 비구조할당 방식으로 useFetchAPI를 두번 호출해야하는 불편함과 단점이 있다.
Version:
  • 1.0.0
Author:
See:
To Do:
  • Promise.all을 사용해서 직렬 Fetch를 병렬 Fetch로 변환해본다.
Properties:
Name Type Description
isData any API에서 반환된 데이터 / default: `null`
isLoading boolean 요청이 진행 중인지 나타내는 상태 / default: `false`
isError Error | null 요청이 실패했을 경우 발생한 에러 객체. 없을 경우 `null` / default: `null`
setUrl string 요청 URL을 설정하거나 업데이트하는 함수 / default: `initialUrl`
Example
// post 요청 시에만 객체 key, value로 설정
const { isData, isLoading, isError, setUrl } = useFetchAPI('/api/data', 'GET', { key: 'value' });
const [isContent, setContent] = useState();

useEffect(() => {
   if (isLoading) {
     console.log('..is Loading');
     setContent('Loading...');
   } else if (isError) {
     console.log(`is Error : `, isError);
     setContent(`Error: `, isError);
   } else if (isData && isData.data) {
     console.log(`Success Contact : `, isData);
     setContent(isData.data);
   } else {
     setContent(null);
   }
 }, [isLoading, isError, isData]);

setUrl('/api/new-data'); // 요청 URL 업데이트
Parameters:
Name Type Attributes Default Description
initialUrl string API 요청을 보낼 초기 URL
method 'GET' | 'POST' | 'PUT' | 'DELETE' <optional>
'GET' 요청에 사용할 HTTP 메서드 (기본값은 'GET')
requestData object | null <optional>
null 요청에 포함될 데이터 (POST, PUT 메서드에서 사용)
Returns:
API 요청 상태들을 담은 객체를 반환합니다.
Type
Object

useGlobalState() → {Object}

Description:
  • `ContextProviderState`에서 제공하는 상태 갑과 상태 변경 함수를 반환하는 커스텀 훅입니다. 반환된 객체를 통해 컴포넌트에서 전역 상태를 쉽게 읽고 업데이트할 수 있습니다.
    context가 정의되지 않았을 경우 에러를 발생시킵니다. (ContextProviderState 외부에서 사용되는 경우)
Version:
  • 1.0.0
Author:
See:
To Do:
  • ContextAPI 대신 Recoil을 사용해 비교해본다.
Example
// 사용할 상태 변수와 상태 변경 함수 기입
const { isState, setState } = useGlobalState();
setState();

// isState, setState 사용 예시
const handleClick = value => {
 setState(value);
 setNum(prev => prev + 1);
 return console.log('in the !handleClick-Fn', isState);
 };
Returns:
`ContextProviderState`에서 제공하는 전역 상태 및 상태 변경 함수들의 객체를 반환합니다.
Type
Object