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

170
Views
Creando el gancho de reacción UseEffect que debe pasar por los datos JSON y cambiar el estado

Estoy tratando de crear filtros para ubicaciones de trabajo ("remoto"/"en persona"/"híbrido") para mi proyecto personal y estuve tratando de solucionarlo durante bastante tiempo (muy nuevo en programación). Estoy seguro de que cometí errores en mi función principal fetchLocationData y pasé URLSearchParams, pero no me sorprendería si hay más errores...

 const fetchLocationData = async () => { const data = await getJobs(); return data.json(); }; useEffect(() => { let condition = fetchLocationData(); switch (jobCondition) { case 'On-site': condition.filter((con) => con.jobLocation === 'in_person'); break; case 'Remote': condition.filter((con) => con.jobLocation === 'remote'); break; case 'Hybrid': condition.filter((con) => con.jobLocation === 'hybrid'); break; default: condition = null; } if (condition != null) { const params = new URLSearchParams({ jobs: jobFilter || null, location: locationFilter || null, since: datePosted || null, conditions: `${condition.con}`, }); history.push({ pathname: '/', search: `${params.toString()}` }); return; } const params = new URLSearchParams({ jobs: jobFilter || null, location: locationFilter || null, since: null, conditions: null, }); history.push({ pathname: '/', search: `${params.toString()}` }); }, [jobCondition]);
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

En lugar de crear una declaración de cambio, puede optimizar un poco su código de esta manera.

 let condition = fetchLocationData(); let obj={'On-site':'in_person','Remote':'remote','Hybrid':'hybrid'} condition =condition.filter((con) => con.jobLocation === obj[jobCondition]);
about 4 years ago · Juan Pablo Isaza Report

0

Hay algunos problemas con su código. Lo reescribí y creo que esto es lo que estás buscando.

No sabía qué tipo de datos getJobs() , pero supongo que es una matriz de objetos porque los está filtrando mientras intenta devolver datos de objetos.

Lo primero es lo primero, saca las cosas de useEffect. Cree su propia función para manejar toda la funcionalidad. Llamémoslo jobFilterHandler .

Este jobFilterHandler se incluirá en un useCallback. Esto se hace porque, si bien la función en sí se llamará en un useEffect, los datos se obtienen y procesan en esta función. Por lo tanto, queremos que esto devuelva un resultado memorizado para evitar la recuperación y la repetición innecesarias de datos.

Agregaré comentarios en el código para explicar lo que hace.

 const jobFilterHandler = useCallback(async (jobCondition) => { // This function takes your filter_condition as an argument and is // asynchronous as marked above. const jobs = await getJobs(); // We retrieve the list of jobs from the API and wait for it. // Here we define the possible filter options to match with the raw data. const condition_options = { "On-site": "in_person", Remote: "remote", Hybrid: "hybrid" }; // From the data we received, we filter the jobs that match our filter. const filtered_jobs = await jobs.filter( (job) => job.jobFilter === condition_options[jobCondition] ); // If there are no filtered jobs, the function ends. if (!filtered_jobs) { return; } // Else the filtered jobs will be returned. return filtered_jobs; }, []); useEffect(() => { // << here you need to write your code to fetch your jobCondition value >> jobFilterHandler(jobCondition).then((jobs) => { // << do whatever you want with the filtered jobs data here >> console.log(jobs); }); }, [jobCondition, jobFilterHandler]);

Código sin comentar aquí.

 const jobFilterHandler = useCallback(async (filter_condition) => { const jobs = await getJobs(); const condition_options = { "On-site": "in_person", Remote: "remote", Hybrid: "hybrid" }; const filtered_jobs = await jobs.filter( (job) => job.jobFilter === condition_options[filter_condition] ); if (!filtered_jobs) { return; } return filtered_jobs; }, []); useEffect(() => { jobFilterHandler(jobCondition).then((jobs) => { console.log(jobs); }); }, [jobCondition, jobFilterHandler]);
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!