markdalgleish/redial

Fetch data from several endpoint for one page with SSR

victortomilin opened this issue · 2 comments

Hi, guys! So, how I can do that? For example, I should render post body and render relative posts for it. And what I do:

I create two actions:

function getPost(id) {
  return (dispatch, getState, { axios }) => {
    return axios.get(path)
      .then(res => {})
      .catch(error => {})
  }
}

function getRelatedPosts(id) {
  return (dispatch, getState, { axios }) => {
    return axios.get(path)
      .then(res => {})
      .catch(error => {})
  }
}

export function getPage(id) {
  return (dispatch, getState) => {
    dispatch(getPost(id));
    dispatch(getRelatedPosts(id));
  }
}

...

// And call this action

const redial = {
  fetch: ({ dispatch, params: { id } }) => dispatch(actions.getPage(id))
}

So, It's look like a aggregator for fetching all needed data from different endpoints. It's best way for my idea? Maybe somebody propose better solution.

I use this library for real project, and I afraid that something go wrong. Help me, please. Thx

What you have done above is fine. However, I would consider having your API optionally "eagerly" return related posts in getPost(id) request.

For example

// GET /api/v1/posts/1234

{
  id,
  title,
  body
}

or

// GET /api/v1/posts/1234?related=true

{
  id,
  title,
  body,
  related [ 
    {
      id,
      title,
      body,
    },
    {
      id,
      title,
      body,
    },
    {
      id,
      title,
      body,
    }
    ...
  ]
}
// 3rd option would be to just return the id's `related [ id, id, id]`  and fetch 
them later (if they are below the fold for example).

Regardless of your decision you should normalize your state tree with normalizr and
write selectors getPostById and getPosts respectively.

Yep, it's have a sense, but not for me. Because my team want to make a frontend server which use different endpoints from different microservices from different servers :)

So.. for myside I found one solution:

const redial = {
  fetch: ({ dispatch, params: { id } }) => {
    return Promise.all([
      dispatch(actions.getPost(id)),
      dispatch(actions.getRelatedPosts(id))
    ]);
  }
}

It's work for me.

@jaredpalmer Thx for you quick answer, I appreciate it, man. I think, I owe you a beer ;)