7.3.1 LogContext에 onRemove 함수 구현하기

    contexts/LogContext.js

    (...)
    
    export function LogContextProvider({children}) {
      (...)
    
      const onModify = (modified) => {
        // logs 배열을 순회해 id가 일치하면 log를 교체하고 그렇지 않으면 유지
        const nextLogs = logs.map((log) =>
          log.id === modified.id ? modified : log,
        );
        setLogs(nextLogs);
      };
      const onRemove = (id) => {
        const nextLogs = logs.filter((log) => log.id !== id);
        setLogs(nextLogs);
      };
    
      return (
        <LogContext.Provider value={{logs, onCreate, onModify, onRemove}}>
          {children}
        </LogContext.Provider>
      );
    }
    
    export default LogContext;

    배열의 내장 함수 filter로 특정 id를 제외한 항목들로만 구성된 새로운 배열을 만들어서 상태를 업데이트해줬습니다. 이렇게 한 이유는 불변성을 유지하면서 배열을 업데이트하기 위해서입니다.

    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.