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

136
Visualizações
elements to the array do not return the current state

For example, I add 10 components.

When I click the show logs button on the 5th line, the first 4 components appear on the console.

But even if I click the button on the 5th line, I want all the components to appear on the console.

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import { observer } from "mobx-react-lite";

function App() {
  const [component, setComponent] = useState([]);

  useEffect(() => {});

  const Test = observer(() => {
    return (
      <div>
        <p>
          Test <button onClick={testFunction("myFunction"))}>Show logs</button>
        </p>
      </div>
    );
  });

  function testFunction(a) {
    console.log(component);
    console.log(a)
  }

  return (
    <div>
      {component.map((Input, index) => (
        <Input key={index} />
      ))}
      <button onClick={() => setComponent([...component, Test])}>
        Click me
      </button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

codesandbox: https://codesandbox.io/s/react-hooks-useeffect-forked-7q15no

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

It seems like the Observer is getting a previous version of component, which is not consistent with the updated component. In cases like this, useEffect is usually a better option as it updates instantly instead of asynchronously. Refer to the code below which is working:

The updater simply makes the useEffect hook run which logs the latest value of component. The onClick now simply updates the updater.

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import { observer } from "mobx-react-lite";

function App() {
  const [component, setComponent] = useState([]);
  const [updater, setUpdater] = useState(0);

  useEffect(() => {console.log(component)}, [updater]);

  const Test = observer(() => {
    return (
      <div>
        <p>
          Test <button onClick={() => setUpdater(updater + 1)}>Show logs</button>
        </p>
      </div>
    );
  });

  return (
    <div>
      {component.map((Input, index) => (
        <Input key={index} />
      ))}
      <button onClick={() => setComponent([...component, Test])}>
        Click me
      </button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
about 4 years ago · Santiago Gelvez 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