const initialState = {
name: '์์ฐจ',
title: '์ฃผ๋์ด๊ฐ๋ฐ์',
mentors: [
{
name: '์ข์์ด',
title: '์๋์ด๊ฐ๋ฐ์',
},
{
name: '์งํ์์ผ',
title: '์๋์ด๊ฐ๋ฐ์',
},
],
};
type State = typeof initialState;
// ์ด๋์ ํน์ ๊ฐ๋ค์ ์งํฉ์ ์๋งํ๋ ์๋ฃํ์ด๋ค.
// ์๋๋ ๋ฌธ์ํ ์ด๋
export enum ACTION_TYPE {
UPDATED = 'updated',
ADDED = 'added',
DELETED = 'deleted',
}
/*
| { type: 'updated', payload: { prev: string, current: string } }
| { type: 'added', payload: { name: string, title: string }}
| { type: 'deleted', payload: { name: string }};
*/
type PersonAction = {
type: ACTION_TYPE,
payload: {
prev?: string;
current?: string;
name?: string;
title?: string;
}
}
export function reducer(
state: State = initialState,
{ type, payload }: PersonAction,
): State {
switch (type) {
case ACTION_TYPE.UPDATED:
return {
...state,
mentors: state.mentors.map((mentor) => {
if (mentor.name === payload.prev) {
return { ...mentor, name: payload.current ?? '' };
}
return mentor;
}),
};
case ACTION_TYPE.ADDED:
return {
...state,
mentors: [...state.mentors, {
name: payload.name ?? '',
title: payload.title ?? '',
}],
};
case ACTION_TYPE.DELETED:
return {
...state,
mentors: state.mentors.filter((mentor) => mentor.name !== payload.name),
};
default:
return state;
}
}
const [person, dispatch] = useReducer(personReducer, initPersonState);