0

I am trying to fetch Cameras from after a specific interval. Once I fetch all cameras, I set camera in local state but if I try to console.log it I get nothing

const [allCameras, setAllCameras] = useState()

const fetchAllCameras = useCallback(async () => {
    try {
      const res = await getAllCameras();
      if(res.data.status_code === 0 && res.data.data){
        setAllCameras(res.data.data)
      }
    } catch (err) {
      console.error(err);
    }
  }, [])

  const _fetchData = useCallback(async () => {
    fetchAllCameras()

    if(allCameras){
      // Nothing gets logged
      console.log("allCameras", allCameras)
    }

  // If I add allCameras as a dependency it triggers an infinite loop
  }, [fetchAllCameras])

  useEffect(() => {
    _fetchData();
    const intervalID = setInterval(() => {
      _fetchData();
    }, FETCH_INTERVAL * 1000);

    return () => clearInterval(intervalID);
  }, [_fetchData]);  
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Shreyas Chorge
  • 127
  • 1
  • 6
  • Could you elaborate on what the goal is ? Your usage of useCallback & useEffect seems a bit redundant, at first glance it can be simplified a lot. Which is why more context on why you are trying to use the hooks will help to give an accurate answer :) – Ian Loubser Nov 16 '21 at 13:44
  • @IanLoubser I want to fetch all Cameras set it in local state and map through all the cameras – Shreyas Chorge Nov 16 '21 at 13:50

1 Answers1

1

Try to apply few fixes to your code:

  • Each useEffect should have a single responsibility.
  • useCallback is debatable unnecessary here (what you trying to memoize? You measured performance issues?)
  • There is a closure on allCameras value, move it to separate useEffect.
const [allCameras, setAllCameras] = useState();

const fetchData = () => {
  const fetchAllCameras = async () => {
    try {
      const res = await getAllCameras();
      if (res.data.status_code === 0 && res.data.data) {
        setAllCameras(res.data.data);
      }
    } catch (err) {
      console.error(err);
    }
  };
  fetchAllCameras();
};

// On Mount
useEffect(() => {
  fetchData();
}, []);

// Interval
useEffect(() => {
  const intervalID = setInterval(() => {
    fetchData();
  }, FETCH_INTERVAL * 1000);

  return () => clearInterval(intervalID);
}, []);

// Check state
useEffect(() => {
  console.log(allCameras);
}, [allCameras]);

Read more at useEffect use cases.

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118