[SOLVED] Moralis Object and Query with useEffect

Hi, I am new to moralis and react. I am trying to fetch data from moralis database on the first rendering by using react hook useEffect(). The function fetchCollectionList() is outside of useEffect() and thus useEffect() cannot access to fetchCollectionList(). I am getting this error

React Hook useEffect has a missing dependency: 'fetchCollectionList'. Either include it or remove the dependency array  react-hooks/exhaustive-deps

I tried to put fetchCollectionList() into useEffect(). It also did not work and getting this error.

React Hook useEffect has missing dependencies: 'Moralis.Object' and 'Moralis.Query'. Either include them or remove the dependency array  react-hooks/exhaustive-deps

I tried other solutions without any success. How can I get it to work?
When I call fetchCollectionList() within component it work but it is called a lot of time.

Here is a code snippet:

const fetchCollectionList = async () => {

    try {

      const dbNFTs = Moralis.Object.extend(CollectionTableName);

      const query = new Moralis.Query(dbNFTs);

      const results = await query.find();

      setCollectionList(results);

      return true;

    } catch (error) {

      console.log(error);

      return false;

    }

  };

  useEffect(() => {

      fetchCollectionList();

  }, []);

this is useEffect

this is where you add dependencies, in that []

You could have such too.

import { useMoralis, useMoralisQuery } from "react-moralis";
  const { isInitialized } = useMoralis();
  const [collectionList, setCollectionList] = useState([]);

  const { fetch } = useMoralisQuery(
    "CollectionTableName",
    (query) => query,
    [],
    { autoFetch: false }
  );

  useEffect(() => {
    isInitialized && fetch({
      onSuccess: (result) => setCollectionList(result)
    })
  }, [isInitialized])
2 Likes

That worked great. Thanks a lot.

I also tried it but without any success. I think I am making something wrong. The solution from qudusayo worked for me. Thank you for your answer.