MERN Stack useEffect problem. Which dependencies should I use?

I have a MERN Stack app. I am fetching data with axios. I have a problem. When I add new data, the data I add does not appear on all devices.

Axios request

export const fetchPosts = createAsyncThunk("posts/fetchPosts", async () => {
  const { data } = await axios.get(URL);
  return data;
});

Api endpoint

const getPosts = async (req, res) => {
  try {
    const data = await Posts.find({});
    res.status(200).json(data);
  } catch (error) {
    console.log(error);
  }
};

When I use the code below, the data I added appears on all devices, but there is an infinity loop.

const { posts } = useSelector((state) => state.posts);
const dispatch = useDispatch();

useEffect(() => {
    console.log("hi");
    dispatch(fetchPosts());
 }, [dispatch, posts]);

When I use this the result is an infinite loop.

enter image description here

If I use this code instead of using the above code

const { posts } = useSelector((state) => state.posts);
const dispatch = useDispatch();

 useEffect(() => {
    console.log("hi");
    dispatch(fetchPosts());
 }, [dispatch]);

The data I added does not appear on all devices. It only appears on the device where I added the data.

As a result, what should I do so that the data I add is seen on all devices at the same time?

Answer

Could you create two useEffect calls, one that handles the initial fetch, and one that repeatedly polls for new data?

const { posts } = useSelector((state) => state.posts);
const dispatch = useDispatch();

// initial fetch
useEffect(() => {
    dispatch(fetchPosts());
 }, [dispatch]);

// poll
useEffect(() => {
    let interval = setInterval(() => dispatch(fetchPosts()), 10000)
    return () => clearInterval(interval)
 }, [dispatch]);