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

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

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 Denunciar

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 Denunciar

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 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