1

enter image description hereI'm trying to save fetched data into variable, but I always get "too many rerenders" or "undefined". What I'm doing wrong

import {
  child,
  get,
  getDatabase,
  ref,
} from "firebase/database";

const db = getDatabase();

function App() {
  const [data, setData] = useState();
  const getData = ref(db);

  useEffect(() => {
    const fetch = () => {
      get(child(getData, "tokens/")).then((snapshot) => {
        const fetched = snapshot.val();
        setData(fetched);
      });
      setTimeout(() => {
        console.log(data);
      }, 500);
    };
    fetch();
  }, []);
}

1 Answer 1

3

There's no need of setTimeout(). You can print the data when the promise is resolved as shown below:

function App() {
  const [data, setData] = useState();
  const getData = ref(db);

  useEffect(() => {
    const fetchData = () => {
      get(child(getData, "tokens/")).then((snapshot) => {
        const fetched = snapshot.val();
        console.log(fetched)
        setData(fetched);
      }); 
    };
    fetchData();
  }, []);
}

Also I've renamed the fetch function to avoid any confusion with Fetch API

Sign up to request clarification or add additional context in comments.

8 Comments

But when I try to call "data" variable, trying to parse it or just log it, i got undefined if it was out of function, and got to many rerenders inside the function
@DaniilGalitskii thats because the promise returned by get might not have resolved yet.. The then block executes when data is received or promise is resolved so data will be logged for sure.. then you set data to state.. unsure why you need to log data there.. checkout stackoverflow.com/questions/14220321/…
@DaniilGalitskii can you share a screenshot with your database and then explain what data are you trying to read?
@DaniilGalitskii Object.values(fetched) can you console log this in then then block and try? Perhaps that's what you are looking for. Then set this in data state and render in UI
You're welcome, checkout MDN its one of the best source to learn JS
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.