0

I'm learning about redux-thunk and don't quite understand the logic here. I'd appreciate if someone could explain the flow. The tutorial I'm following does this:

//App.js
useEffect(() => {
        dispatch(getPosts());
    }, []);

//actions.js
export const getPosts = () => async (dispatch) => {
    try {
        const { data } = await api.fetchPosts();
        dispatch({ type: 'FETCH_ALL', payload: data });
    } catch (error) {
        console.log(error.message);
    }
};

//reducers.js
export default (posts = [], action) => {
    switch (action.type) {
        case 'FETCH_ALL':
            return action.payload;
        case 'CREATE':
            return [...posts, action.payload];

        default:
            return posts;
    }
};

Couldn't we just call getPosts() inside of useEffect func instead of dispatching it since it'll dispatch within our action creator. If not, couldn't we just return the object we wanted to dispatch within our action creator instead of dispatching it and let the first dispatch then dispatch said object. I'm not sure what I'm missing here

  • 2
    Do you read this doc? https://redux.js.org/usage/writing-logic-thunks#why-use-thunks – Lin Du May 23 '22 at 11:08
  • @slideshowp2 yea after some digging I learned that it's necessary to dispatch the function so that it's intercepted by the middleware, which will then allow you to dispatch an action within a given function. Thank you though this is also very helpful – anonjay001 May 25 '22 at 19:37

0 Answers0