Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

103
Views
¿Cómo puedo manejar esta API con sus diferentes formas de ordenar datos en mi página?

Estoy llamando a una API que muestra datos de juegos en React. La API en sí ofrece una forma de ordenar sus datos y filtrarlos por categoría, consola, etc. Sé cómo llamar a la API para mostrar su contenido en mi página de índice. Pero si quiero ofrecerle al usuario la posibilidad de ordenar esos datos de la forma en que la API me lo ofrece, ¿cómo debo proceder? Estoy usando AXIOS, por cierto. Aquí está el código.

 const App = () => { const [games, setGames] = useState([]); const options = { method: 'GET', url: 'example.com/api/games', headers: { 'x-host': 'example.com', 'x-key': 'xxx' } }; const getGames = () => { axios.request(options) .then((response) => { const games = response.data; setGames(games); }) .catch((error) => { console.error(error); }); } useEffect(()=>{ getGames(); },[]) return ( <div className="container"> { games.map((game)=>{ const {id, title, platform, publisher, thumbnail} = game; return ( <div key={id} className="item"> <img src={thumbnail}/> <h1>{title}</h1> <h2>{platform}</h2> <h3>{publisher}</h3> </div> ) }) } </div>

En la página de la API, la forma en que se especifica para solicitar una clasificación o filtrado de la información de la API es cambiando la URL y agregando encabezados. Por ejemplo

 var options = { method: 'GET', url: 'https://example.com/api/games/filters', params: {platform: 'browser', category: 'mmorpg', 'sort-by': 'release-date'}, headers: { 'x-host': 'example.com', 'x-key': 'xxx' } };

Entonces, básicamente, ¿cómo debo mostrar estas diferentes formas de llamar a los datos de la API en mi propia página? ¿Debo escribir funciones diferentes cada vez? Obviamente soy un principiante en esto, así que pido disculpas si es una pregunta tonta.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Haga que la platform , category , sortBy , releaseDate sea una especie de variable de estado que el usuario pueda cambiar a través de un botón/entrada, luego haga esto...

 const getGames = () => { const params = { platform, category, 'sort-by': sortBy, 'release-date': releaseDate } axios.request({...options, params}) .then((response) => { const games = response.data; setGames(games); }) .catch((error) => { console.error(error); }); }
about 4 years ago · Juan Pablo Isaza Report

0

Me gustaría algo como esto:

 const [games, setGames] = useState([]); // I'll only use sortBy for the example but it will be the same for other params const [sortBy, setSortBy] = useState(""); // Make this an async function that receives the options as a parameter const getGames = async (opt) => { // optional await, you can still use promises if you want try { const response = await axios.request(opt); setGames(response.data); } catch (err) { console.error(error); } } useEffect(()=>{ // Pass the options const you created to this effect that will only run when the component mounts getGames(options); },[])

Ahora cree un botón de selección para adjuntar el estado sortBy y otro useEffect para observar los cambios de estado para ese valor:

 useEffect(()=>{ // Here you will add the other params if necessary if (sortBy) { getGames({...options, params: { sortBy } }); } // Update the dependency array for each param you add. },[sortBy]) const handleChange = (event) => { setSortBy(event.target.value); } return ( {/* rest of your jsx */} <select value={sortBy} onChange={handleChange}> <option value="">None</option> <option value="title">Title</option> <option value="platform">Platform</option> <option value="publisher">Publisher</option> </select> )

Entonces, básicamente, puede ver un ejemplo de trabajo usando sortBy y suponiendo que sortBy es una cadena que contiene el campo por el que desea ordenar, si necesita pasar otro valor, simplemente adapte el valor sortBy para tener la forma que necesita pasar a la API.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!