dope the
dope the

Reputation: 21

Get data from Firebase with React

function Editor({ userObj }) {

  const [myContents, setMyContents] = useState([]);
  const [loading, setLoading] = useState(true);

useEffect(() => {
    const db = dbService.collection("contents").onSnapshot((snapshot) => {
      if (snapshot.size) {
        const communityArray = snapshot.docs.map((doc) => ({
          id: doc.id,
          ...doc.data(),
        }));
        setMyContents(communityArray);
        setLoading(false);
        console.log(loading);
      } else {
        setLoading(false);
      }
    });
    return () => {
      db();
    };
  }, []);
  setTimeout(() => {
    console.log(loading);
    console.log("4", myContents[0].id);
  }, 1000);

error img

I don't know why the message appears so many times.

When I print console.log(loading) after setLoading(false), I don't know why it shows true.

When using the setTimeout function, the id value is displayed after an error.

Is it necessary to use async for the id to come out properly?

Upvotes: 1

Views: 129

Answers (1)

Tin Huynh
Tin Huynh

Reputation: 179

You can check React.StrictMode in app.js or index.js, it will duplicate render. You can try remove it.

You want it run in your code, pls check it has a value before log console.log("4", myContents[0] && myContents[0].id);

After that useEffect run, it will re-call setTimeout when it call setMyContents(communityArray); setLoading(false);

Upvotes: 0

Related Questions