0

I am working on react native application I use firebase as my backend. I fetch data from firebase real time database and render it on the page. But now I want my application to be supported offline.

I used following two functions for rendering. For listings from database

  const loadListings = () => {
    let data = [];
    listingRef.orderByChild("created_at").on("value", (snapshot) => {
      data = [];
      snapshot.forEach((listing) => {
        data.push(listing.val());
      });
      cache.store("listings", data.slice(0, 10)); // only stores latest ten listings
      setListings(data);
      setLoading(false);
    });
  };

and then use it inside useEffect like.

  useEffect(() => {
    loadListings();
  }, []);

and for listings from cache I used this.

  const loadListingsCached = async () => {
    let data = await cache.get("listings");
    setListings(data);
  };

Now I cant put a check inside firs function as effect hook will run only one time and initialy network status is null. its not defined. how do I achieve this? by the way link to package I used for detecting connectivity

Edit I used this hook as second argument to useEffect() but didn't work for me

  const netInfo = useNetInfo();

I

Saad Ramay
  • 152
  • 1
  • 11

1 Answers1

0

What you want to achieve is make the code different depending on what is the network status. In the answer linked by @Rohit there is my answer about how to check the network connectivity with Net Info Package.

What you have to do is make the effect dependant on the status change. You should pass it as a argument to the effect.

 const netInfo = useNetInfo();
 useEffect(() => {
   loadListings();
 }, [netInfo]);

This way the code will always run when a network change is detected. I hope this is what you wanted to achive. Please be more specific about you goal and what is the problem. Current questions does not specify if the hook is not working, or the rendering function does not trigger etc.

twboc
  • 1,452
  • 13
  • 17