React interactive sorting table - How to keep input during sorting?

Viewed 129

I'm new to React and I'm doing an interactive sorting table. Both the interaction and sorting work fine apart, but if I sort the table, add a row and change input my unsorted table loses the inputs (because I make a temporary copy of my unsorted data before sorting to get the unsorted data). This could probably be solved by keeping track of which row goes where, but I can't quite figure out how to do it. Is there a way to map some unique row index along with the sorting? I'll also include parts of code for reference.

    this.state={
        data:[{}],
        datatemporary:[{}], //store unsorted data when sorting
        dataindex:[], //used as key when mapping rows
        dataint:0, //grows, uses .push at dataindex to add unique keys
        sorted:0, 
        sorteddesc:0,
        sortindex:0 //keeps track of which column is sorted
    };
    compareBy = (key) => {
        if (this.state.sorted===0) {
            this.setState({sorted:1,datatemporary:[...this.state.data]})
            return(
                function(a, b) {
                    if (a[key] < b[key]) return -1;
                    if (a[key] > b[key]) return 1;
                    return 0;
                }
            )
        }
        if (this.state.sorteddesc===0) {
            this.setState({sorteddesc:1})
            return function(a, b) {
                if (a[key] < b[key]) return 1;
                if (a[key] > b[key]) return -1;
                return 0;
                }; 
        }
    };
    sortBy = (key,index) => {
        if (this.state.sorted===1 && this.state.sorteddesc===1) {
            let datatemp=this.state.datatemporary
            this.setState({sorted:0,sorteddesc:0,data:datatemp,datatemporary:[{}],sortindex:0})
        } else {
            let datatemp = [...this.state.data];
            datatemp.sort(this.compareBy(key));
            this.setState({data: datatemp,sortindex:index});  
        }
      };
0 Answers
Related