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

285
Visualizações
Issues upgrading async componentDidMount() to async useEffect()

// UPDATE: The issue was using the state immediately after setting it inside useEffect(). See my answer HERE for details.

I'm trying to upgrade one of my React app pages from class component to functional component with Hooks. However, I have some issues due to some async functions.

The way the old page behaves is that in componentDidMount() some data is async fetched from the database and displayed. It works properly, myName and myValue are displayed correctly.

// OLD APPROACH - CLASS COMPONENT


    class MyPage extends Component {
      constructor(props) {
        super(props);
    
        this.state = {
          myName: null,
          myValue: undefined,
        }
      }
    
      componentDidMount = async () => {
    
        try {
          const myName = await getNameFromDatabase();
          const myValue = await getValueFromDatabase();
    
    
          this.setState({ myName, myValue });
    
        } catch (error) {
          alert(
            "Some errors occured when fetching from DB"
          );
          console.error(error);
        }
      }
    
      render() {
    
        return (
          <div>
            <h1>{this.state.myName}</h1>
            <h1>{this.state.myValue}</h1>
          </div>
        )
    
      }
    
    export default MyPage

I tried to update the page by carefully following this response.

// NEW APPROACH - FUNCTIONAL COMPONENT WITH HOOKS

    function MyPage() {
    
      const [myName, setMyName] = useState(null);
      const [myValue, setMyValue] = useState(undefined);
    
      useEffect(() => {
       
        async function fetchFromDatabase() {
         
          const myName = await getNameFromDatabase();
          const myValue = await getValueFromDatabase();
    
          setMyName(myName);
          setMyValue(myValue);
    
        }
    
        fetchFromDatabase();
      }, [])
    
      return (
        <div>
          <h1>{myName}</h1>
          <h1>{myValue}</h1>
        </div>
      )
    
    }

However, when I do this, they no longer get displayed. I supposed they remain "null" and "undefined". Apparently if I do a console.log(), they eventually get fetched, but only after the page is rendered without them, which is not what was happening in the first case.

Why exactly is this happening? Why is it getting displayed correctly in the first case but not in the second? As far as I know, useEffect() does the same thing as componentDidMount(). Should I proceed another way if I wish to call async functions inside useEffect()?

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

0

The useEffect hook and state updates are fine. Function components are instanceless though, so the this is just undefined. Fix the render to just reference the state values directly.

It's also good practice to handle errors when working with asynchronous code.

function MyPage() {
  const [myName, setMyName] = useState(null);
  const [myValue, setMyValue] = useState(undefined);

  useEffect(() => {
    async function fetchFromDatabase() {
      try {
        const myName = await getNameFromDatabase();
        const myValue = await getValueFromDatabase();

        setMyName(myName);
        setMyValue(myValue);
      } catch(error) {
        // handle any rejected Promises and thrown errors
      }
    }

    fetchFromDatabase();
  }, []);

  return (
    <div>
      <h1>{myName}</h1>
      <h1>{myValue}</h1>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza Relatório

0

First of all, you are giving the same name for your response as your useState(). Try using different names. Then, put just empty string into your useState() default value instead of null or undefined. Finally, you no longer need to use this but instead access directly the value. It should be something like this :

function MyPage() {

  const [myName, setMyName] = useState('');
  const [myValue, setMyValue] = useState('');

  useEffect(() => {
   
    async function fetchFromDatabase() {
     
      const name = await getNameFromDatabase();
      const value = await getValueFromDatabase();

  setMyName(name);
  setMyValue(value);

}

fetchFromDatabase();
  }, [])

  return (
    <div>
      <h1>{myName}</h1>
      <h1>{myValue}</h1>
    </div>
  )

}
about 4 years ago · Juan Pablo Isaza Relatório

0

function MyPage() {
  const [myName, setMyName] = useState(null);
  const [myValue, setMyValue] = useState(undefined);

  useEffect(() => {
    (async () => {
      const myName = await getNameFromDatabase();
      const myValue = await getValueFromDatabase();

      setMyName(myName);
      setMyValue(myValue);
    })();
  }, []);

  return (
    <div>
      <h1>{myName}</h1>
      <h1>{myValue}</h1>
    </div>
  );
}

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