Home > Enterprise >  Populating a state after getting a document from the Firestore
Populating a state after getting a document from the Firestore

Time:06-25

I'm building a CRUD and in the edit step I'm trying to populate the edit fields with data from the specific document. I managed to bring the data from Firestore, but I am not able to put the data in the state, it remains empty. Any idea how I do this?

import { doc, getDoc } from "firebase/firestore";
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { db } from "../Firebase/firebase";

export default function EditData() {
  const [company, setCompany] = useState({});
  const params = useParams();

  useEffect(() => {
    const getData = async () => {
      const docRef = doc(db, "companies", params.id);
      const docSnap = await getDoc(docRef);
      setCompany({ ...docSnap.data() });
      console.log(docSnap.data());
      console.log(company);
    };
    getData();
  }, [params.id]);

  return (
    <div>
      Form here.
    </div>
  );
}

console.log

CodePudding user response:

Set state is an asynchronous operation, so the value will not update in the next line.

If you want to ensure that the company has been updated, Maybe you can use it in the UI, or maybe you can use useEffect hook with company dependance ( which will execute it's callback whenever the company state change )

useEffect(() => console.log(company), [company])

CodePudding user response:

setCompany tells React to enqueue the update, but doesn't actually perform it.

You can 'react' to the update with a second useEffect:

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

Also note that adding:

<div>{JSON.stringify(company)}</div>

will show the change, because the change (once processed) will trigger a re-render.

  • Related