Search code examples
javascriptreactjsreduxreact-reduxredux-actions

React redux, action payload cannot see variable within a try/catch block


I'm trying to put the variable "result" in the action payload but it cannot be defined because it is within the try block. I'm not sure how to work around this. I'm still new to Redux and here is the action itself.

export const fetchMovies = async (endpoint, category) => {
    const isLoadMore = endpoint.search('page');
    try{
        const result = await (await fetch(endpoint)).json();
    } catch(error){
        this.setState({error: true});
        console.log(error);
    }

    return{
        type: HomeActionTypes.FETCH_MOVIES,
        payload: result, category, isLoadMore
    }
}

I've tried initializing result at the top using let but it did not resolve the issue. Also, I'm not sure if I'm setting the payload correctly with the variables I have set within them. For example, they are needed to be used within the reducer and my guess is to call the items within the payload as action.payload.result, action.payload.category, action.payload.isLoadMore wherever I need to use them within the reducer. Is that the correct way to do it? Thanks for any contributions to helping answer my questions.


Solution

  • You can take different approaches. First one, the one you are trying, you must declare the variable result as let (so you can modify its value) in the correspondent lexical scope, so in this case outside of the try brace and inside the function declaration so the return can access its value.

    export const fetchMovies = async (endpoint, category) => {
        const isLoadMore = endpoint.search('page');
        let result = null
        try{
            result = await (await fetch(endpoint)).json();
        } catch(error){
            this.setState({error: true});
            console.log(error);
        }
    
        return{
            type: HomeActionTypes.FETCH_MOVIES,
            payload: result, category, isLoadMore
        }
    }
    

    Another approach, that I'd rather follow, would be to move all the logic of the happy flow in the try brace and manage the action returned in the error flow in the catch brace:

    export const fetchMovies = async (endpoint, category) => {
        try{
            const isLoadMore = endpoint.search('page');
            const result = await (await fetch(endpoint)).json();
            return{
              type: HomeActionTypes.FETCH_MOVIES,
              payload: result, category, isLoadMore
            }
        } catch(error){
            // Rather than modifying the state, use a defined error action to trigger the proper error flow and logic.
            console.log(error);
            return{
              type: HomeActionTypes.FETCH_MOVIES_ERROR, // To be defined in the way you desire to be able to manage it as the execution of this action
              payload: error
            }
        }
    }