Home > Net >  Component making two api calls from single dispatch
Component making two api calls from single dispatch

Time:07-30

i have a problem where my component is making two api calls instead of one. I am using react and react-redux with reactjs/toolkit. I tried different solutions like changing dependancy array in useEffect hook, changing request headers, looking through entire codebase to find another call. Nothing worked. I also tried this but it did not work. Why does my fetch query run multiple times in my React component

I want this code to call api once, soon after component is mounted.

Redux dev tools shows that there are two api call. One right after another. Sceenshoot of actions in dev tools.

Here api call is dispatched.

useEffect(() => {
    dispatch(fetchPosts('hot', ''));
  }, [dispatch]);

Entire project is here: https://github.com/chpiotr06/Reddit-minimal/tree/dev

Fetching thunk looks like this:

export const fetchPosts = createAsyncThunk(
  'wall/fetchPosts',
  async (type, querry) => {
    const response = await Reddit.fetchPosts(type, querry);
    const data = await response.json();
    return data;
  }
)

Reddit.fetchPosts (Work in progress):

const Reddit = {
  fetchPosts: (type, querry) => {
    return fetch(`https://www.reddit.com/${type}.json`, {
      method: 'GET',
      mode: 'cors',
    })
  },
}

CodePudding user response:

Not sure if that's the right guess, but could it have to do with the strictmode? If you comment out <React.StrictMode> in index.js, does it still render twice?

(this should really be a comment and not an answer, but I don't have enough credits for that)

  • Related