Skip to content
This repository has been archived by the owner. It is now read-only.

Data fetching - on load vs on demand? #577

Closed
moshekatz opened this issue Feb 6, 2019 · 1 comment
Closed

Data fetching - on load vs on demand? #577

moshekatz opened this issue Feb 6, 2019 · 1 comment

Comments

@moshekatz
Copy link

@moshekatz moshekatz commented Feb 6, 2019

Hi there!
I'm wondering when to use one over the other (or maybe a combination of both)?

Things to consider:

  1. Handling a lot of requests (I guess with some sort of caching)
  2. The data doesn't change very often, and even if it does - it's ok to wait for a page refresh

Stuff I though about

Fetching on load:

  • (-) slows down initial load
  • (-) handling race conditions for some use cases (therefore probably introducing additional async API)
  • (+) after a single request, I can access the data synchronously through cache (most use cases)
// onLoadApi.js
const cache = {};

/* ...fetching logic to fill the cache... */

const get = key => cache[key];
const getAsync = key => /* reading from cache or waiting for the response */

export { get, getAsync }

// usageOnLoad.js
import { get, getAsync } from './onLoadApi'; 

const value = get('key');
const otherValue = await getAsync('otherKey');

Fetching on demand:

  • (+) no effect on initial loading
  • (-) accessing the data asynchronously in all use cases
  • (+) no need for multiple API's, always returns a Promise
// onDemandApi.js
const cache = {};

const getAsync = key => /* reading from cache or fetching from server */

export { getAsync }

// usageOnDemand.js
import { getAsync } from './onDemandApi'; 

const anyValue = await getAsync('key');
@kentcdodds
Copy link
Owner

@kentcdodds kentcdodds commented Feb 7, 2019

Hi @moshekatz!

Here's your audio answer!

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
2 participants