choo icon indicating copy to clipboard operation
choo copied to clipboard

Fetching data for a view

Open callum opened this issue 10 years ago • 5 comments

I have some views that depend on data from a remote source, but I can't figure out where the request(s) should happen. I'm trying to keep the HTTP code separate from my views so that requests aren't made every time the app renders. Any advice here?

callum avatar Jun 26 '16 22:06 callum

Are the data coming in based on a user action or does it arrive by default when the page loads?

If its on a user action you could call a method from an effect and when it finishes call send in the callback (effects are async).

If not you could use some sort of events (an emitter, a pull stream, etc) to trigger in a subscription (like the SSE example).

Does that make sense?

On Jun 26, 2016, at 15:47, callum [email protected] wrote:

I have some views that depend on data from a remote source, but I can't figure out where the request(s) should happen. I'm trying to keep the HTTP code separate from my views so that requests aren't made every time the app renders. Any advice here?

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub, or mute the thread.

toddself avatar Jun 26 '16 22:06 toddself

Hi @toddself - it arrives by default when the page loads. What makes this slightly more tricky is that it requires the params and state of the current view/route to be able to request the correct data.

callum avatar Jun 26 '16 22:06 callum

Can you attach a listener to DOM content loaded which requests the content and then have that fire a subscription when it arrives?

On Jun 26, 2016, at 15:56, callum [email protected] wrote:

Hi @toddself - it arrives by default when the page loads. What makes this slightly more tricky is that it requires the params and state of the current view/route to be able to request the correct data.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub, or mute the thread.

toddself avatar Jun 26 '16 22:06 toddself

@callum one approach is to store whether or not the data has been fetched in the state, and fetch it in the view if isFetched = false (demo). An alternative is to use on-load to detect when the view is mounted to the dom. This is being incorporated into choo v3 though there's still an outstanding issue with it.

timwis avatar Jun 26 '16 23:06 timwis

Solved using a global cache of fetched URLs:

const cache = require('./cache')

// model
const uri = 'http://localhost:8080/albums'
if (cache.has(uri)) return
const opts = {
  headers: { authorization: window.localStorage.token },
  json: true
}
http.get(uri, opts, (err, res, body) => {
  if (err || res.statusCode >= 400) {
    return send('app:error', { error: 'Something went wrong' })
  }
  cache.add(uri)
  send('albums:gotAll', { albums: body.data })
})

callum avatar Jun 27 '16 00:06 callum