reaver lover
reaver lover

Reputation: 674

React.js Table Sorting with Dynamic Data

There are two different API Service Endpoints of some dynamic data like below.

// from API Service A, All value are realtime changing
{
 stack : 10
 over : 2
 flow : 4
}
// from API Service B, All value are realtime changing
{
 stack : 4
 over : 1
 flow : 2
}

key from two different API services are the same, but the value is different by real-time changes.

so I want to notate these differences with the table.

I coded to display this data table with react.js like below.

import { useState, useEffect } from 'react';
function App(){
 const [commonKey, setCommonKey] = useState([stack, over, flow]);
 const [dataA, setDataA] = useState({});
 const [dataB, setDataB] = useState({});

 useEffect(()=> {
  // ...periodically fetch data from API Service A and setDataA(response)
  // ...periodically fetch data from API Service B and setDataB(response)
 } ,[]);

 return (
 <>
  <table>
   <thead>
    <th>key</th>
    <th>valueA</th>
    <th>valueB</th>
    <th>A-B</th> // sorting function needed by this field value(A minus B).
   </thead>
   <tbody>
    commonKey.map((keyField)=>{
     <Mytr key={keyField} keyField={keyField} dataA={dataA[keyField]} dataB={dataB[keyField]} />
    });
   </tbody>
  </table>
 </>
)}

function Mytr({keyField, dataA, dataB}){
 return (
 <>
  <tr>
   <td>{keyField}</td>
   <td>{dataA}</td>
   <td>{dataB}</td>
   <td>{dataA - dataB}</td> // sorting function needed by this field value.
  </tr>
 </>
)}

export default App;

How can I add sort by A-B value function in this situation?

p.s Sorry for my Poor English.

Upvotes: 1

Views: 2706

Answers (1)

Amila Senadheera
Amila Senadheera

Reputation: 13245

You can sort the commonKeys in the useEffect hook like below.

  useEffect(() => {
    // ...periodically fetch data from API Service A and setDataA(response)
    // ...periodically fetch data from API Service B and setDataB(response)

    // get a copy of the commonKey array
    const newArr = [...commonKey];
    // sort the keys using differece of two consecutive diffs
    newArr.sort((p, q) => dataA[p] - dataB[p] - (dataA[q] - dataB[q]));
    // set the sorted array to state
    setCommonKey(newArr);
  }, []);

To avoid the scrolling issue, keep the scrollY position saved and scroll to that position once commonKey is updated within a useLayoutEffect.

 useEffect(() => {
    const updatePosition = () => {
      setCurrentScrollY(window.scrollY);
    };
    window.addEventListener("scroll", updatePosition);
    updatePosition();
    return () => window.removeEventListener("scroll", updatePosition);
  }, []);

  useLayoutEffect(() => {
    window.scrollTo(0, currentScrollY);
  }, [commonKey]);

Edit pensive-mountain-blgb4

Upvotes: 1

Related Questions