React Ag-grid state 동기화 문제

허주환·2022년 10월 25일
0

React

목록 보기
1/2
post-thumbnail

Summary

  • Polymer에서 React로 리펙토링을 진행중
  • ag-grid 라이브러리를 사용하여 data table을 구성
  • useState로 할당한 buttonType이 ag-grid의 onRowDoubleClicked 이벤트에서 데이터 동기화 문제가 발생

발생

  • buttonType
enum ButtonType {
  Type1 = 'type1',
  Type2 = 'type2',
  // ...
}

const [btnType, setBtnType] = useState<ButtonType>(ButtonType.Type1);
  • 어디선가 setBtnType 호출
setBtnType(ButtonType.Type2);
  • onRowDoubleClicked
onRowDoubleClicked(e: RowDoubleClieckedEvent) {
  console.log(`btnType: ${btnType}`);
  if (btnType === Button.Type2 && ...) {
  	// ...    
  }
}
  • 기대된 결과값: type2
  • 출력된 결과값: type1
  • 이전 값이 들어가 있는 것을 log로 볼 수 있음

해결1

// ...
const [gridOptions, setGridOptions] = useState<GridOptions>({
  
  // ...
  onRowDoubleClicked(e: RowDoubleClickedEvent) {
    const { type, ... } = e.context;
    console.log(`btnType: ${type}`);
    if (type === ButtonType.Type2 && ...) {
        // ...		
    }
  },
}
// ...
<AgGridReact
    gridOptions={gridOptions}
    context={{type: btnType, ...}}
  />
  • ag-grid api 문서를 보면서 props에 context를 발견
    • en: The context object is passed to most of the callbacks used in the grid.
    • ko: grid에 대부분의 콜백들에게 전달되는 객체
  • context에 props로 btnType 전달
  • 기대된 결과값: type2
  • 출력된 결과값: type2

해결2 (추가 - 22.10.26)

// ...
const onRowDoubleClicked = (e:RowDoubleClickedEvent) => {
  console.log(`btnType: ${btnType}`);
  if (btnType === ButtonType.Type2 && ...) {
  	// ...    
  }
}
// ...
<AgGridReact
    gridOptions={gridOptions}
    onRowDoubleClicked={onRowDoubleClicked}
  />
  • 코드 리뷰에서 gridOptions 초기 세팅에 이벤트를 등록하면 위와 같은 동기화 문제를 격을 수 있어 AgGridReact의 props에 이벤트를 등록하면 해결 할 수 있다는 피드백을 받아 props로 이벤트를 전달해 보았다.

  • 기대된 결과값: type2

  • 출력된 결과값: type2

참고

  • ag-grid-react context props (링크)
profile
Junior BE Developer

0개의 댓글