Reputation: 4187
I am trying to figure out how best to work with react, redux and an autocomplete component. At this present time, I am using react-select. The issue I have is around when and where to make the API call to retrieve the autocomplete results.
There are two ways I have attempted to solve this problem:
Make the API call from inside the component or via a callback passed in from the container wrapping the component. This works just fine for me. I imagine unit testing it is a little less tidy as a result of it.
Raise a redux action on a keystroke. In the action creator make the API call. With the use of redux-thunk middleware, the promise is resolved and a new action is raised with the search results as it's payload and is stored in some part of the store. The autocomplete component has been listening to this list and renders the list of results. I partly got this working with the react-select but the state of the input component is getting wiped out on subsequent keystrokes.
I looking for guidance on the advantages/disadvantages of either approach and if there is best practice here to adopt.
Thanks.
Upvotes: 1
Views: 1291
Reputation: 4187
In case, anyone lands here looking for an update.
After working with react for months now and having more experience, I can mention here the path I took.
While it's possible to store the autocomplete results in a redux store, there is little advantage to this. I did implement this as an experiment. Since these results are ephemeral for the user, it's perfectly reasonable to store inside the components state. This is this final approach I took.
As an aside, if the autocomplete is used multiple times on a page, there is a case to potentially cache results against search queries to reduce requests on the server and improve client-side perf. I decided to use redux here to share the data across the multiple instances of the autocomplete in my situation.
I also changed the autocomplete library from react-select to downshift to gain more control over the implementation of my autocomplete.
YMMY as always.
Upvotes: 1