Search code examples
reactjsgoogle-cloud-firestorereact-hooksnext.jsreact-functional-component

React doesn't re-render my component when the array is changed?


I've set different options for sorting various listings, and i've set an empty array for my listings. using firebase for backend, so basically everything is working, but the data isn't displayed after useEffect does it's work. as soon as I change the sort option the listings appear. after refreshing it is the same again. I'm passing the listings and sort as props to another child component which is a grid layout. Everytime I've to manually change the sort so see data, how can it be so that it automatically show's the data according to the sort option.

const [sort, setSort] = useState("option1");
  const [listings, updateListings] = useState([]);

  const db = getFirestore();
  const colRef = collection(db, "Listing");

  useEffect(() => {
    let defaultListings = [];
    getDocs(colRef)
      .then((snapshot) => {
        snapshot.docs.forEach((doc) => {
          defaultListings.push({ ...doc.data(), id: doc.id });
        });
      })
      .catch((err) => {
        console.log(err.message);
      });
    updateListings(defaultListings);
  }, []);
 return(<Listing list = {listings} sortoption={sort} />)

this listing component shows the grid

i've tried adding dependencies, but it results in an infinite loop, while without any dependencies the component doesn't show anything.


Solution

  • You need to call updateListings inside then, otherwise it will run before you modify the defaultListings array.

    So:

    getDocs(colRef)
      .then((snapshot) => {
        snapshot.docs.forEach((doc) => {
          defaultListings.push({ ...doc.data(), id: doc.id });
        });
        updateListings(defaultListings); // 👈
      })
      .catch((err) => {
        console.log(err.message);
      });