kriasoft / universal-router

A simple middleware-style router for isomorphic JavaScript web apps
https://www.kriasoft.com/universal-router/
MIT License
1.7k stars 104 forks source link

api call optimize #128

Closed frozenfung closed 6 years ago

frozenfung commented 6 years ago

Hey teams, I am confused where to make api calls in the universal. Let's say I have to route A and route B

route A need data from C api and D api. route B need data from C api and E api.

Now I use put C api call in middleware in action.

{
  path: 'subRoot',
  action() {
    // call C api
    // combine data from C api and child
    // return child
  },
  children: [{
    path: 'A',
    action() {
      // call D api
      // return 
    }
  }, {
    path: 'B',
    action() {
      // call D api
      // return 
    }
  }

But I found that actually I do not need data from C api everytime route/url change. I only need it in server-side rendering and first time I switch to subRoot in client. Am I put these apis in the wrong places?

thanks

frenzzy commented 6 years ago

If you need to do something server-side only it is not isomorphic/universal code. You can add condition for this case

if (process.env.SERVER) { // or similar
  // server-side only stuff here
}

Another way is to share the result of such request between client and server side.

const route = {
  path: '/news',
  async action({ store, fetch }) {
    if (!store.news) {
      store.news = await fetch('/api/news');
    }
    return { title: 'News Page', component: <News news={store.news} /> };
  },
};

and transfer store form server to client like here

frozenfung commented 6 years ago

Currently it works with a solution like the store thing, thanks 👍