Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

163
Vistas
Creating UseEffect react hook which should go through JSON data and switch the state

I'm trying to build filtering for job locations ("remote"/"in-person"/"hybrid") for my personal project and I was trying to troubleshoot it for quite some time (very new to programming). I am sure I made mistakes in my main fetchLocationData function and passing URLSearchParams but I am not gonna be surprised if there are more mistakes.....

      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 Respuestas
Responde la pregunta

0

Rather than creating switch statement you can somewhat optimize your code this way.

 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 Denunciar

0

There's a few issues with your code. I rewrote it and I think this is what you're looking for.

I did not know what kind of data getJobs() returned but I'm presuming it's an array of objects because you are filtering through it while trying return object data.

First thing first, move stuff out of useEffect. Create it's own function to handle all of functionality. Let's call it jobFilterHandler.

This jobFilterHandler will be wrapped in a useCallback. This is being done because while the function itself will be called in a useEffect, the data is being fetched and processed in this function. So we want this to return a memoized result to prevent unnecessary data fetching and re-renders.

I will add comments in the code to explain what it does.

    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]);

Uncommented code here.

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda