Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

281
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!