Redux: Calling one action from another action creator

duhaime picture duhaime · Jan 2, 2018 · Viewed 16.3k times · Source

I'm working on a Redux app in which many filter components can change the nature of a search to be performed. Any time the state of one of those filter components changes, I want to re-run a search action. I can't seem to call the search action from each of the filter components correctly, however.

Here's the main search action:

// actions/search.js
import fetch from 'isomorphic-fetch';
import config from '../../server/config';

export const receiveSearchResults = (results) => ({
  type: 'RECEIVE_SEARCH_RESULTS', results
})

export const searchRequestFailed = () => ({
  type: 'SEARCH_REQUEST_FAILED'
})

export const fetchSearchResults = () => {
  return (dispatch, getState) => {
    // Generate the query url
    const query = getSearchQuery();  // returns a url string
    return fetch(query)
      .then(response => response.json()
        .then(json => ({
          status: response.status,
          json
        })
      ))
      .then(({ status, json }) => {
        if (status >= 400) dispatch(searchRequestFailed())
        else dispatch(receiveSearchResults(json))
      }, err => { dispatch(searchRequestFailed()) })
  }
}

fetchSearchResults works fine when I call it from connected React components. However, I can't call that method from the following action creator (this is one of the filter action creators):

// actions/use-types.js
import fetchSearchResults from './search';

export const toggleUseTypes = (use) => {
  return (dispatch) => {
    dispatch({type: 'TOGGLE_USE_TYPES', use: use})
    fetchSearchResults()
  }
}

Running this yields: Uncaught TypeError: (0 , _search2.default) is not a function. The same happens when I run dispatch(fetchSearchResults()) inside toggleUseTypes.

I'm definitely making a rookie mistake--does anyone know how I can resolve this problem and call the fetchSearchResults method from the actions/use-types.js action? I'd be very grateful for any advice others can offer on this question!

Answer

Cory Danielson picture Cory Danielson · Jan 2, 2018

I see 2 errors

  1. You're importing the fetchSearchResults function incorrectly
    • This is where the TypeError _search2.default is coming from.
    • Uncaught TypeError: (0 , _search2.default) is not a function
  2. You're dispatching the fetchSearchResults action/thunk incorrectly

Error 1: Incorrect import

// This won't work. fetchSearchResults is not the default export
import fetchSearchResults from './search';
// Use named import, instead.
import {fetchSearchResults} from './search';

Error 2: Incorrect action usage

// This won't work, it's just a call to a function that returns a function
fetchSearchResults()
// This will work. Dispatching the thunk
dispatch(fetchSearchResults())