Sharing data
Answered
Blue Picardy Spaniel posted this in #help-forum
Blue Picardy SpanielOP
When the user loads the website I want to do a single request to my API. I want the results of this request to be shared among all client and server components. How would I go about this?
11 Replies
@Blue Picardy Spaniel When the user loads the website I want to do a single request to my API. I want the results of this request to be shared among all client and server components. How would I go about this?
you can do that, by using the data cache. This cache is handled by your server and will be equal for all users. So fetch your stuff and put it in data cache. If another user would fetch the same now, he will get the same result as you got
@B33fb0n3 you can do that, by using the data cache. This cache is handled by your server and will be equal for all users. So fetch your stuff and put it in data cache. If another user would fetch the same now, he will get the same result as you got
Blue Picardy SpanielOP
the data is different for each user though
i want their username, pfp, etc
@Blue Picardy Spaniel the data is different for each user though
Oh, I misread your question. If you put your data fetching function inside a react.cache, your request to a specific resource will be "deduped". That means, that you can call the same function in mutliple components and only one request will be send to the data source, but ALL components get the same set of data. On the next request, there would be the same procedure
@B33fb0n3 Oh, I misread your question. If you put your data fetching function inside a react.cache, your request to a specific resource will be "deduped". That means, that you can call the same function in mutliple components and only one request will be send to the data source, but ALL components get the same set of data. On the next request, there would be the same procedure
Blue Picardy SpanielOP
do you have any docs for this?
Answer
When getMetrics is first called with data, getMetrics will call calculateMetrics(data) and store the result in cache. If getMetrics is called again with the same data, it will return the cached result instead of calling calculateMetrics(data) again.
@B33fb0n3 sure: https://react.dev/reference/react/cache
Blue Picardy SpanielOP
thanks, what about dealing with the client side though?
@Blue Picardy Spaniel thanks, what about dealing with the client side though?
clientside shouldn't fetch data directly. Share data via props or use a fetching library like react query or swr
Blue Picardy SpanielOP
thank you
@Blue Picardy Spaniel thank you
Happy to help. Please mark solution