0

I have designed a table which will read a object array and a dropdown list for ordering control.

However, when I select other ordering value in dropdown list. The front end table did not update at the same time. It will have a delay, please see the following example.

T0: default select order by "name" -> front end correct(Order by "name")

T1: select order by "age" -> front-end no update (still order by "name")

T2: select order by "name" -> front-end update (order by "age")

T3: select order by "age" -> front-end update (order by "name")

My object array

var data = [
    {
        key: 1,
        name: 'AAA',
        age: '10',
    },
    {
        key: 2,
        name: 'BBB',
        age: '8',
    },
    {
        key: 3,
        name: 'name',
        age: '12',
    },
]
const [listData, setListData] = useState(data);

Drop down control

const handleOrderChange = (value) => {
    setOrderValue(value);
};

useEffect(() => {
    console.log(orderValue.value); //match what I click
    switch (orderValue.value) {
        case 'name':
            listData.sort((a, b) => (a.name > b.name ? 1 : -1));
            break;
        case 'age':
            listData.sort((a, b) => (a.age> b.age? 1 : -1));
            break;
        default:
            console.log('Default');
    }
    console.log(listData); //match what I expected
}, [orderValue]);

Front-End

{/* Data */}
        {listData.map((item) => (
            <DataDetail
                key={item.key}
                name={item.name}
                age={item.age}
            ></DataDetail>
        ))}
0o0SkY0o0
  • 121
  • 1
  • 10

1 Answers1

0

You should never mutate a state variable as this:

    switch (orderValue.value) {
            case 'name':
                listData.sort((a, b) => (a.name > b.name ? 1 : -1));
                break;
            case 'age':
                listData.sort((a, b) => (a.age> b.age? 1 : -1));
                break;
            default:
                console.log('Default');
        }

instead you should use:

useEffect(() => {
    switch (orderValue.value) {
            case 'name':
                const listDataCopy = [...listData]
                listDataCopy.sort((a, b) => (a.name > b.name ? 1 : -1));
                setListData(listDataCopy)
                break;
            case 'age':
                const listDataCopy = [...listData]
                listDataCopy.sort((a, b) => (a.age> b.age? 1 : -1));
                setListData(listDataCopy)
                break;
            default:
                console.log('Default');
        }
}, [orderValue, listData, setListData]);
Sinan Yaman
  • 5,714
  • 2
  • 15
  • 35