Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda