maxwellgover
maxwellgover

Reputation: 7121

Updating component state inside of useEffect

I'm playing around w/ hooks for the first time. In my component I make a request for some data inside of useEffect then want to save that data to local state. I try using setUser inside of useEffect but state never gets updated. I've tried it w/o the second argument [] but I get an infinite loop. I know setState is asynchronous and previously you could specify a function as a second argument to setState which would run when state had updated.

I'm wondering what the correct process is for updating state inside of useEffect

import React, { useEffect, useState } from 'react';
import { withRouter } from 'react-router-dom';

import { db } from '../../constants/firebase';

function Profile(props) {
  const [ user, setUser ] = useState(null);
  const { username } = props.match.params;

  useEffect(() => {
    db.collection("users").where("username", "==", username)
      .get()
      .then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
          console.log(doc.data()); // data comes back fine
          setUser(doc.data());
          console.log(user); // user is still null
        });
      })
      .catch((error) => {
        console.log("Error getting user: ", error);
      });
  }, [username])

  return <div>Profile</div>
}

export default withRouter(Profile);

Upvotes: 1

Views: 1708

Answers (2)

Prithviraj Sahu
Prithviraj Sahu

Reputation: 214

You can use another useEffect which will run when user updates.

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

Upvotes: 1

Doppio
Doppio

Reputation: 2188

Try change 2nd argument of useEffect from [username] to [props.match.params.username]

Upvotes: 1

Related Questions