0

i'm fetching data from this two online API, the first api is randomly organized and the second api is ranking organized, the data outcome when both api put together i get API#2POSITION, API#1NAME, API#2POINTS but randomly organized by API#1.

[1]enter image description here

How can i sort().map my code so the outcome on the table is organized by 1,2,3etc ranking

code:

import axios from "axios";
import React, { useState, useEffect } from "react";
import Pagination from "https://cdn.skypack.dev/[email protected]";


const News = () => {
  const [playerName, setPlayerName] = useState([]);
  const [playerRank, setPlayerRank] = useState([]);
  const [player, setPlayer] = useState([]);
  const [perPage, setPerPage] = useState(10);
  const [size, setSize] = useState(perPage);
  const [current, setCurrent] = useState(1);
  const [players, setPlayers] = useState();

  const fetchData = () => {
    const playerAPI = 'http://localhost:3008/api/players';
    const playerRank = 'http://localhost:3008/api/highscore/players';

    const getINFOPlayer = axios.get(playerAPI)
    const getPlayerRank = axios.get(playerRank)
    axios.all([getINFOPlayer, getPlayerRank]).then(
      axios.spread((...allData) => {
        const allDataPlayer = allData[0].data.players
        const getINFOPlayerRank = allData[1].data.players
        const newPlayer = allDataPlayer.map(name => {
          const pr = getINFOPlayerRank.find(rank => name.id === rank.id)


          return {
            id: name.id,
            name: name.name,
            status: name.status,
            position: pr?.position,
            score: pr?.score
          }

          // or simply do the following if the keys doesn't matter: return {...name, ...pr}
        })

        setPlayerName(allDataPlayer)
        setPlayerRank(getINFOPlayerRank)

        console.log(newPlayer)
        setPlayer(newPlayer)
      })
    )
  }
  useEffect(() => {
    fetchData()
  }, [])

  const PerPageChange = (value) => {
    setSize(value);
    const newPerPage = Math.ceil(players.length / value);
    if (current > newPerPage) {
      setCurrent(newPerPage);
    }
  }

  const getData = (current, pageSize) => {
    // Normally you should get the data from the server
    return player?.slice((current - 1) * pageSize, current * pageSize);
  };

  const sortData = getData && player?.sort((a, b) => a.position > b.position ? 1 : -1)

  const PaginationChange = (page, pageSize) => {
    setCurrent(page);
    setSize(pageSize)
  }

  const PrevNextArrow = (current, type, originalElement) => {
    if (type === 'prev') {
      return <button><i className="fa fa-angle-double-left"></i></button>;
    }
    if (type === 'next') {
      return <button><i className="fa fa-angle-double-right"></i></button>;
    }
    return originalElement;
  }


  return (
    <>
      <div className="container-fluid mt-5 mb-5">
        <div className="row justify-content-center">
          <div className="col-md-10">
            <div className="card">
              <div className="card-body p-0">

                <div className="table-filter-info">

                  <Pagination
                    className="pagination-data"
                    showTotal={(total, range) => `Showing ${range[0]}-${range[1]} of ${total}`}
                    onChange={PaginationChange}
                    total={player.length}
                    current={current}
                    pageSize={size}
                    showSizeChanger={false}
                    itemRender={PrevNextArrow}
                    onShowSizeChange={PerPageChange}
                  />
                </div>
                <div className="table-responsive">
                  <table className="table table-text-small mb-0">
                    <thead className="thead-primary table-sorting">
                      <tr>
                        <th>#</th>
                        <th>Name</th>
                        <th>Points</th>
                        <th>Alliance</th>
                        <th>Status</th>
                      </tr>
                    </thead>
                    <tbody>
                      {getData(current, size)
                        .map((player) => {
                          return (
                            <tr key={player.name}>
                              <td>{player.position}</td>
                              <td>{player.name}</td>
                              <td>{player.score}</td>
                              <td>{player.alliance}</td>
                              <td>{player.status}</td>
                            </tr>
                          );
                        })}
                    </tbody>
                  </table>
                </div>
                <div className="table-filter-info">

                  <Pagination
                    className="pagination-data"
                    showTotal={(total, range) => `Showing ${range[0]}-${range[1]} of ${total}`}
                    onChange={PaginationChange}
                    total={player.length}
                    current={current}
                    pageSize={size}
                    showSizeChanger={false}
                    itemRender={PrevNextArrow}
                    onShowSizeChange={PerPageChange}
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  )
}


export default News

1 Answer 1

1

to sorting any data in ReactJS just use following code-

const sortData = apiData && apiData.sort((a, b) => a.name > b.name ? 1 : -1)

In the above code ApiData is sorted you can change it with the constant name which get the data. After this use sorting method, just call two values like a and b then compare them and return the result. You can also change a.name with pr?.position for sorting the API result.

Hope you'll like the example and solve your query. If you still facing issue lemme know, i will help you more. Thanks

Sign up to request clarification or add additional context in comments.

8 Comments

hello brother, thanks for answering my question really appreciate the help. i'm still new to coding i put together this code over a month now can you tell me how would i implement this code? do i have to add const [ sortData, setsortData ] = useState() to the top of the page?
nope you didn't need to create state, just edit the code and pass the same code that i mention just change a.name and b.name with position or with thing that you want to sorting
hey friend, i did what you told me : const sortData = getData && player?.sort((a, b) => a.position > b.position ? 1 : -1) and it does works but not 100% it gets the #1 Rank and then it jumps to randoms numbers. any idea why? do you want me to update the post with a picture of whats happening?
yupp please update the code and picture for better result..
just updated the code and added picture, you can see your line by half way into the code
|

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.