Skip to content

Instantly share code, notes, and snippets.

@leo424y
Created December 5, 2016 12:29
Show Gist options
  • Select an option

  • Save leo424y/70efe7a35d7783543a020b2719e291de to your computer and use it in GitHub Desktop.

Select an option

Save leo424y/70efe7a35d7783543a020b2719e291de to your computer and use it in GitHub Desktop.
thunk middleware

thunk MIDDLEWARE 好棒棒


thunk MIDDLEWARE 目的

處理非同步 fucntion 如各種 API


thunk MIDDLEWARE 步驟

  • 寫一個MIDDLEWARE 處理非同步function
  • 處理非同步function
  • 根據 STATE 改變 VIEW 值

寫一個 MIDDLEWARE 處理非同步function

非同步function需等待API回傳,故MIDDLEWARE需能等回傳後再次讓 DISPATCHER 接著做事

const thunk = store => next => action => {
  if(typeof action === 'function'){
      action(store.dispatch, store.getState());
  }else{
      next(action);
  }
}

處理非同步function

var asyncIncrease = (dispatch, state) => {
    dispatch({type:"INCREMENT_LOADING"});
    _fakeServerApi.increaseCount(state.count.result,
        data => dispatch({ type: 'INCREMENT' }));
}

模擬API延遲幾秒後處理function

var _fakeServerApi = {
    // imitate the server API
    increaseCount :  ( currentCount, cb ) =>
        setTimeout(()=> cb(currentCount + 1), 5000)
    }

用真的API達成非同步

var getRandomImages = (dispatch, state) => {
  dispatch({ type: 'IMAGES_LOADING' });
  var imgurAPI = "https://api.imgur.com/3/gallery/random/random/1";
  $.getJSON(imgurAPI).done(data => dispatch({ type: 'IMAGES', data:data.data}))
}

根據 STATE 改變 VIEW 值

定義要在VIEW顯示的值為變數status,待API回傳後讓STATE更新stauts

if(state.count.loading){
    $('
---

#status').text("is loading...");
}else{
     $('
---

#status').text("loaded");
}

  • 好好利用,讓debug之路順暢
  • 好好利用,讓VIEW聽話
  • 好好利用,讓UX提升
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment