1
    const dispatch= useDispatch();
    const [places,setPlaces] = useState([]);  
    useEffect(() => {
        if(bounds.sw && bounds.ne){
        getPlacesData(type,bounds.sw,bounds.ne)
        .then((data) => {
            console.log({data});
            setPlaces(data.filter((place) => place.name && place.num_reviews > 0));
            console.log({places});
            dispatch(setGlobalPlaces(places))
        });
        }
    },[type,bounds])

Getting empty places array in console even after setting places using setPlaces. Only after change in type or change in bounds, "places" hook is getting updated.

skyboyer
  • 22,209
  • 7
  • 57
  • 64

2 Answers2

2

This behavior is intended as calls to setState() are async. You cannot see changes right after setState(). You could use a new useEffect() on [places] to see the changes in the console log.

useEffect(() => {
  console.log(places);
}, [places]);
Kai W
  • 119
  • 11
1

setPlaces is action async which means if you want to log a new value of places try this in another hook

 const dispatch= useDispatch();
    const [places,setPlaces] = useState([]);  
    useEffect(() => {
        if(bounds.sw && bounds.ne){
        getPlacesData(type,bounds.sw,bounds.ne)
        .then((data) => {
            console.log({data});
            setPlaces(data.filter((place) => place.name && place.num_reviews > 0));
            console.log({places});
            dispatch(setGlobalPlaces(places))
        });
        }
    },[type,bounds])

    useEffect(() => {
       console.log({places});
    },[places])

Detail in here https://reactjs.org/docs/hooks-overview.html

Anhdevit
  • 1,926
  • 2
  • 16
  • 29