Search code examples
reactjsreduxredux-thunk

React redux using state within an action creator


I'm trying to create an action creator with a method that used to be within my component's logic. I understand how to turn it into an action creator; however, I'm not sure how to work around the ternary operator as it relies on something that was coming from the local state. this.state.searchTerm as well as this.state.data.currentPage is needed for the code to work the way I need it to work.

export const loadMoreMovies = () => {
    return dispatch => {
        const searchEndpoint = `${SEARCH_BASE_URL}${this.state.searchTerm}&page=${this.state.data.currentPage + 1}`;
        const popularEndpoint = `${POPULAR_BASE_URL}&page=${this.state.data.currentPage + 1}`;

        const endpoint = this.state.searchTerm ? searchEndpoint : popularEndpoint;

        dispatch(fetchMovies(endpoint, 'search'));
    }
}

Also, could anyone confirm for me from what you see within the action creator? Is there any reason to create a reducer for this action creator? I don't seem to see any reason for one since it's not used to change the state but I'd like others opinion of that. Thanks


Solution

  • When working with redux-thunk, the function you return from an action creator can have two arguments, the second one being a function that gives you the current state:

    export const loadMoreMovies = () => {
      return (dispatch, getState) => {
        const state = getState();
        const searchEndpoint = `${SEARCH_BASE_URL}${state.searchTerm}&page=${state.data.currentPage + 1}`;
        const popularEndpoint = `${POPULAR_BASE_URL}&page=${state.data.currentPage + 1}`;
    
    
    
        const endpoint = state.searchTerm ? searchEndpoint : popularEndpoint;
    
        dispatch(fetchMovies(endpoint, 'search'));
      }
    }