April 10, 2019

Moving from Redux to React Hooks Part 2

Moving from Redux to React Hooks Part 2

In the previous part we defined our store and hooked it up to our Provider which passes down our state to its child components. I'd like to keep the same structure as I used with redux but we have the problem that the dispatch function is not available in our actions since we don't have any middleware like in redux that injects it for us, also the architecture is quite different. So what we are going to pass the dispatch method down to our action, which returns a function that calls dispatch with the desired action. This might sound confusing, so let us look at some example.

export const getComments = () => (dispatch) => {
    dispatch(getCommentsRequest());
    
    fetch(url)
        .then(res => res.json())
        .then(json => {
            dispatch(getCommentsSuccess(json));
        })
        .catch(err => dispatch(getCommentsFailure(err)));
}

In the example above we see the traditional way once we used redux-thunk to access the dispatch method within our actions, we simply return a function and pass it dispatch. Since we do not have redux-thunk, we do it the following way.

export const getComments = (dispatch) => () => {
    dispatch(getCommentsRequest());
    
    fetch(url)
        .then(res => res.json())
        .then(json => {
            dispatch(getCommentsSuccess(json));
        })
        .catch(err => dispatch(getCommentsFailure(err)));
}

We simply pass dispatch to getComments directly once we use it in our components. Then in our component we need to assign the return value to a variable we then can call whenever we want to dispatch our action within the useEffect hook.

const action = getComments(token.dispatch);

useEffect(() => {

    action();

}, context.state)

>>> Check out my Udemy courses.