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

262
Visualizações
React - useEffect JSON object with same content but disordered fields

I am fetching JSON data from my firebase server, and sometimes, it has disordered fields.

I want to run a useEffect when the content of the json object changes... but, trying to do the following

useEffect(() => {}, [JSON.stringify(data)]);

doesn't work correctly because of the disordered fields.

I have made an snack, simulating my current scenario.

How can I solve this?

Note: It seems that it could be better to avoid the state update... any ideas?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

From this answer: https://stackoverflow.com/a/3849480/8861638

We can compare two objects deeply with this function, as it uses recursion, it's guaranteed to go all the way in.

function countProps(obj) {
    var count = 0;
    for (k in obj) {
        if (obj.hasOwnProperty(k)) {
            count++;
        }
    }
    return count;
};

function objectEquals(v1, v2) {

    if (typeof(v1) !== typeof(v2)) {
        return false;
    }

    if (typeof(v1) === "function") {
        return v1.toString() === v2.toString();
    }

    if (v1 instanceof Object && v2 instanceof Object) {
        if (countProps(v1) !== countProps(v2)) {
            return false;
        }
        var r = true;
        for (k in v1) {
            r = objectEquals(v1[k], v2[k]);
            if (!r) {
                return false;
            }
        }
        return true;
    } else {
        return v1 === v2;
    }
}

Now, we can take the advantage of the objectEquals function to do a comparison between the new and the existing data prop in that component.

First, we want to keep track of the data when it comes so we can compare it to the future ones, we can use the useRef hook comprehensively so we don't trigger any re-render.

// data is our initial state.
const savedData = useRef(data || {});

Then, we can customize the useEffect to listen to the comparison of the savedData and the new coming data and see whether there is a change or not.

const dataChanged = objectEquals(data, savedData.current);

useEffect(() => {
  if (dataChanged) {
    savedData.current = data;
    // Do something...
  }
}, [dataChanged])
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