1

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?

  • From the perspective of the user of your site: Does the result returned by the search depend on on which page I used the search box? If I made a search on page 1, then switched to page 2 (also with a search box) and switched back, would I get the search results of page 1 back? Would that also be the case if I did an additional search on page 2? – Bart van Ingen Schenau Jan 3 '18 at 10:08
  • The search isn't specific to the page. Doing the search displays the search results page, regardless of origin. – Stu Pegg Jan 3 '18 at 11:41
  • Actually, I say that, but I may end up using these results elsewhere. The actual use case is a list of customers. In one place I'm searching for a customer to add a new item to. In another (future requirement) I'm searching for a customer to view. – Stu Pegg Jan 3 '18 at 11:43
  • What middleware are you using to make the request? – Daniel T. Jan 6 '18 at 20:09
  • @DanielT. request today, axios tomorrow. – Stu Pegg Jan 7 '18 at 9:46
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.