1

I want to sort the items according to their Id like in ascending so how to do it?

heres the code from react component i used...

import { useState, useEffect} from "react"
//styles
import './ItemList.css'

export default function ItemList() {

const[Items,setItems]=useState([])


useEffect(() => {

    fetch('http://localhost:3000/data')
    .then(response=>response.json())
    .then(json=>setItems(json))
   
}, [])


console.log(Items)

return (
    <div className="item-list">
        <h1>Item List</h1>
        <ul>
            {Items.map(data=>(

            <li key={data.id}>
            <h2>{data.id}</h2>
            <h3>{data.name}</h3>
            </li>

            ))}
        </ul>
        
    </div>
)
}
2
  • The best method is to include pagination and sort in API itself. if you need it in UI then(json=>setItems(json.sort(....//your sort condition))) Commented Dec 15, 2021 at 6:23
  • Agreed. Ideally that would be done on the server, but if it has to be front-end the answer below will work Commented Dec 15, 2021 at 6:30

1 Answer 1

2

Pagination might create problems if you sort on the front end.

use array sort for frontend, I'm assuming id is number

fetch("http://localhost:3000/data")
  .then((response) => response.json())
  .then((json) => setItems(json.sort((a, b) => a.id - b.id)));

If it's a string

fetch("http://localhost:3000/data")
  .then((response) => response.json())
  .then((json) => setItems(json.sort()));
Sign up to request clarification or add additional context in comments.

2 Comments

Note: This is assuming item.id is type number. (I think it probably is, too.)
Yes, that's correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.