✅ Getting data from api on app startup?
I am experimenting with a very simple app. I want to keep a list of pokemon that I get from an api in a variable so that when a user searches in the front end for a name, the dotnet api will search do a string search on this list for similar names and return to the client to be rendered in a typeahead. Not sure how to make my api make an "automatic" http request for data without user interaction
12 Replies
So the flow is, my front end <> my dotnet api <> external api
what's your frontend?
React
If the goal is to fetch something once and then keep re-using it in your program / API, I think a good approach is to wrap it in a
Lazy<T>
I kind of know how to do this. I could just make it so that the first request made to the api will get the pokemon list and store it, and then subsequent requests wont need to request it anymore. But im curious if theres some kind of pattern for getting data asynchronously on start up and store in some kind of service for later use?
This is a console program but the basic idea should work fine in your API / service:
If you don't want to lazily fetch it you can just put the code to populate it inline in your services startup code.
I think Lazy is better in most cases.
When does this lazy do the api call?. I dont need to await it in Main?
your front end would make a GET call on initialize and probably would want store that list in the front end
I had thought of that but for learning purposes I wanted to know how to keep all of this server side and just return the list of matches
The first time you try to access the data it will go fetch it. Subsequently it will be cached and re-used.
Ahh got it
Ty
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.