React Pivot Grid State Persistence

    The Ignite UI for React State Persistence in React Pivot Grid allows developers to easily save and restore the grid state. When the IgrGridState is applied on the React IgrPivotGrid, it exposes the getState, getStateAsString, applyState and applyStateFromString methods that developers can use to achieve state persistence in any scenario.

    Supported Features

    IgrGridState다음 기능들의 상태 저장 및 복원을 지원합니다:

    • Sorting
    • Filtering
    • CellSelection
    • ColumnSelection
    • Expansion
    • IgrPivotConfiguration
      • Pivot Configuration properties defined by the IPivotConfiguration interface.
      • 피벗 차원 및 값 기능은 애플리케이션 수준 코드를 사용하여 복원됩니다. 피벗 구성 복원 섹션을 참조하세요.

    Usage

    이 메서드는getState 모든 상태 정보를 포함하는 객체의IgrGridStateInfo 그리드 상태를 반환합니다. 이를 구하기 위해 추가 절차가 필요할 수 있습니다.

    이 도구는getStateAsString 직렬화된 JSON 문자열을 반환하기 때문에 개발자들은 이를 가져와 데이터베이스, 클라우드, 브라우저 localStorage 등 어떤 데이터 저장소에도 저장할 수 있습니다.

    개발자는 기능 이름이 있는 배열을 인수로 전달하여 특정 기능에 대한 상태만 가져오도록 선택할 수 있습니다. 빈 배열은 기본 상태 옵션을 사용하게 됩니다.

    <IgrPivotGrid>
        <IgrGridState ref={gridStateRef}></IgrGridState>
    </IgrPivotGrid>
    
    // get an `IgrGridStateInfo` object, containing all features original state objects, as returned by the grid public API
    const state: IgrGridStateInfo = gridStateRef.current.getState([]);
    
    // get all features` state in a serialized JSON string
    const stateString: string = gridStateRef.current.getStateAsString([]);
    
    // get the sorting and filtering expressions
    const sortingFilteringStates: IgrGridStateInfo = gridStateRef.current.getState(['sorting', 'filtering']);
    

    applyState- 메서드는 객체를IgrGridStateInfo 인자로 받아들이며, 객체나 지정된 특징에서 발견된 각 특징의 상태를 두 번째 인자로 복원합니다.

    applyStateFromString- 메서드는 직렬화된 JSON 문자열을 인자로 받아들이며, JSON 문자열이나 지정된 두 번째 인자로 지정된 각 특징의 상태를 복원합니다.

    gridStateRef.current.applyState(gridState, []);
    gridStateRef.current.applyStateFromString(gridStateString, []);
    gridStateRef.current.applyState(sortingFilteringStates, [])
    

    객체는options 인터페이스를 구현하므로IgrGridStateOptions, 각 키(특정 기능의 이름)마다 해당 기능 상태가 추적될지 여부를 나타내는 불리언 값이 있습니다.getState /getStateAsString 메서드는 이 특징들의 상태를 반환된 값에 넣지 않으며,applyStateapplyStateFromString 메서드는 해당 특징들의 상태를 복원하지 않습니다.

    <IgrGridState options={{ cellSelection: false, sorting: false }}></IgrGridState>
    

    사용하기 쉬운 단일 포인트 API는 단 몇 줄의 코드만으로 완전한 상태 영속성을 달성할 수 있게 합니다. 아래에서 코드를 복사해서 붙여넣으세요. 사용자가 현재 페이지를 떠날 때마다 브라우저LocalStorage 객체에 그리드 상태를 저장합니다. 사용자가 메인 페이지로 돌아올 때마다 그리드 상태가 복원됩니다. 매번 복잡한 고급 필터링과 정렬 표현식을 설정할 필요가 없고, 한 번만 설정하면 아래 코드가 나머지 작업을 사용자 대신 처리해 주세요:

    <IgrPivotGrid onRendered={restoreGridState}>
        <IgrGridState ref={gridStateRef}></IgrGridState>
    </IgrPivotGrid>
    
    useEffect(() => {
        restoreGridState();
        window.addEventListener('beforeunload', saveGridState);
        return () => {
          window.removeEventListener('beforeunload', saveGridState);
        }
    }, []);
    
    // Using methods that work with IgrGridStateInfo object.
    const saveGridState = () => {
        const state = gridStateRef.current.getState([]);
        window.localStorage.setItem('grid-state', JSON.stringify(state));
    }
    
    const restoreGridState = () => {
        const state = window.localStorage.getItem('grid-state');
        if (state) {
            gridStateRef.current.applyState(JSON.parse(state), []);
        }
    }
    
    //Or using string alternative methods.
    const saveGridState = () => {
        const state = gridStateRef.current.getStateAsString([]);
        window.localStorage.setItem('grid-state', state);
    }
    
    const restoreGridState = () => {
        const state = window.localStorage.getItem('grid-state');
        if (state) {
            gridStateRef.current.applyStateFromString(state, []);
        }
    }
    

    Restoring Pivot Configuration

    IgrGridState will not persist pivot dimension functions, value formatters, etc. by default (see limitations). Restoring any of these can be achieved with code on application level. The IgrPivotGrid exposes two events which can be used to set back any custom functions you have in the configuration: DimensionInit and ValueInit. Let's show how to do this:

    • Assign event handlers for the DimensionInit and ValueInit events:

    The DimensionInit and ValueInit events are emitted for each value and dimension defined in the pivotConfiguration property.

    • In the ValueInit event handler set all custom aggregators, formatters and styles:
      const onValueInit = (event: IgrPivotValueEventArgs) => {
        const value: IgrPivotValueDetail = event.detail;
        if (value.member === "AmountofSale") {
          value.aggregate.aggregator = totalSale;
          value.aggregateList?.forEach((aggr: any) => {
            switch (aggr.key) {
              case "SUM":
                aggr.aggregator = totalSale;
                break;
              case "MIN":
                aggr.aggregator = totalMin;
                break;
              case "MAX":
                aggr.aggregator = totalMax;
                break;
            }
          });
        } else if (value.member === "Value") {
          value.styles.upFontValue = (rowData: any, columnKey: any): boolean =>
            parseFloat(rowData.aggregationValues.get(columnKey.field)) > 150;
          value.styles.downFontValue = (rowData: any, columnKey: any): boolean =>
            parseFloat(rowData.aggregationValues.get(columnKey.field)) <= 150;
        }
      }
    

    Demo

    Limitations

    • getState method uses JSON.stringify() method to convert the original objects to a JSON string. JSON.stringify() does not support Functions, thats why the IgrGridState directive will ignore the pivot dimension MemberFunction, pivot values member, Formatter, custom aggregate functions, styles and pivot configuration strategies: columnStrategy and rowStrategy.