简体   繁体   中英

How to cache autocomplete suggestions data react

I have a generic medicine database in MongoDB, has about 3500 documents in it. I want to use medicine names and brand names in autocomplete input fields in the React web app.

The data might look like this:

{
"_id": {
    "$oid": "5ed9bf1087263e1ef3d65288"
},
"name": "Ethamsylate + Mefenamic acid",
"brands": [
    {
        "name": "STOP-MF",
        "package": "Tablet",
        "strength": " ",
        "price": "120.00"
    },
    {
        "name": "SYLATE-M 500",
        "package": "Tablet",
        "strength": " ",
        "price": "156.00"
    },

],
}

Data will not change very often, so I want to cache it client-side right at the initial load. I have been googling about this. What I found is:

  1. Making HTTP requests for each newly typed character is bad.
  2. LocalStorage API is easy to use, but data will need to be compressed
  3. IndexedDb offers unlimited storage, but the API is quite complex

I haven't found much about other storage options in the browser. Thanks for any and all help!

Tried SWR, but it makes an HTTP request every time I reload the page, can't have that as the request takes 5-8 seconds to fetch data, I want to store data locally in browser somehow

have you try swr ? it may help you cache data at client side:D

Making HTTP requests for each newly typed character is bad.

It is not always bad, it depends on your use case. Would you say google search is badly implemented because it makes requests as you type? Not quite. You can also use throttle and debounce to somewhat limit amount of requests. But if you need offline access and your DB is relatively small then you have other options of course.

IndexedDb offers unlimited storage, but the API is quite complex

Have you tried to use some wrapper around it? Like maybe https://github.com/dfahlander/Dexie.js would fit for you?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM