0
votes

First of all, I'm sorry if the first question is unfamiliar and difficult to understand

Purpose: Get data from firestore and fetch again when list of store is updated.

add info. I want to get data from a firestore and redraw the screen when the list of stores is updated.

This is a general list update.

problem: useEffect wants to execute fetch when the value of stores is updated, but useEffect is always called and fetch request to firestore does not stop.

The code is below.

Test.jsx

...
import { useDispatch, useSelector } from "react-redux";
import { fetchStores } from "../../reducks/stores/operations";
const storesRef = db.collection('stores');

const Test = () => {
    const dispatch = useDispatch();
    const selector = useSelector(state=>state);
    // stores set initialState
    // stores: {
    //   name: "",
    //   list: [],
    // }
    const stores = selector.stores.list;

    useEffect(()=>{
        dispatch(fetchStores())
    },[stores])
}
...

reducks/stoers/operations.js

 export const fetchStores = () => {
    return async (dispatch) => {
      storesRef.where().get()
        .then(snapshots => {
          const storeList = []
          snapshots.forEach(snapshot => {
            const store = snapshot.data();
            store['id'] = snapshot.id;
            storeList.push(store)
          })
          dispatch(fetchStoresAction(storeList))
        })
    }
  }

*fetchStoresAction saves an array in the store list.

thank you

1

1 Answers

1
votes

You should have an empty dependency array in useEffect so the fetch request only executed once when the components gets mounted:

useEffect(() => {
  dispatch(fetchStores())
}, [])

If you would like to fetch stores when new store is created or updated, you should do it in a function where you can access the update or create fetch request's result. If the result is successful (successful update on database), then you can fetch your stores again.