Question

I have a search box I'm going to use on different pages (I use the term 'page' loosely here).

  • The search box puts its value (the search string) into the Redux state.
  • The results are populated from an external API
  • Another component displays the results of the search as a list.

Example state:

{
    searchString: 'Cheeeese',
    results: [
        'I like Cheeeese!',
        'There is no Cheeeese!!',
    ],
}

What's baffling me is this - if there are multiple search boxes (on different 'pages') where do I put the responsibility for requesting the results from the API?

  • There's more than one place the search box is used, so the search box (nor a wrapper of the search box) can be responsible without duplicate calls.
  • The Redux action should not have a side-effect, so the reducer can't be responsible.
  • Each page shouldn't be responsible, since this would lead to code duplication.

The nearest thing to sanity I can find is a non-rendering component whose sole purpose is to watch the searchString state entry, and fire off a request to the API (updating results on response).

Is this a reasonable approach, or is my component structure itself the problem?

Was it helpful?

Solution

Having thought about this for a good long while, I can see that one of my assertions is wrong:

  • There's more than one place the search box is used, so the search box (nor a wrapper of the search box) can be responsible without duplicate calls.

I was thinking that the API call would be prompted by the component's property changing, which would lead to multiple requests from multiple components.

In reality, the API call can be triggered from the individual component's update event without fear of duplication - only that instance of the component is being updated by the user.

Licensed under: CC-BY-SA with attribution
scroll top