티스토리 뷰

React- Google analytics e-commerce 관련 이벤트 달기


> e-commerce 관련 함수


react에 google analytics e-commerce관련한 docs도 많이 없을뿐더러, 적용에도 많은 애를 먹었어서 기록을 남긴다.


function createTransaction(orderData) {
 const ga = ReactGA.ga();
 return (
   new Promise(resolve => {
     // create a timeout to always resolve. this is in case there is a problem
     // sending the items/transaction
     const timeout = setTimeout(() => {
       console.log('Google analytics transaction timed out');
       resolve();
    }, 3000);

     // this will be called after the transaction and all
     // items are sent to the server. once all elements have been
     // sent, it will resolve the promise.
     let hits = orderData.menuInfos.length + 1; // items + transaction
     const hitCallback = function() {
       hits -= 1;
       if (hits === 0) {
         clearTimeout(timeout); // clear the timeout so promise doesn't resolve twice
         console.log('Google analytics transaction sent');
         resolve();
      }
    };

     // process the transaction and all items
     ga('require', 'ecommerce');
     ga('ecommerce:addTransaction', {
       id: orderData.userIdx,
       revenue: orderData.totalPrice,
       shipping: orderData.deliveryPrice,
       hitCallback, // fires when tx send is done
    });
     orderData.menuInfos.forEach(menuinfo => {
       ga('ecommerce:addItem', {
         id: orderData.userIdx,
         name: menuinfo.idx,
         category: orderData.serviceType,
         quantity: menuinfo.amount,
      });
    });
     ga('ecommerce:send');
  })
     // handle a hard failure conditions gracefully (ie: ga didn't load)
    .catch(ex => {
       console.log('Error sending Google analytics transaction');
       console.log(ex);
    })
);
}

위의 함수를 redux의 saga 안에 넣어주자. 그리고 난후 주문실행관련 함수가 실행될때,


export function* placeOrder(actions) {
 const { orderData } = actions;
 co(function*() {
   // yield any promise
   const result = yield put(createTransaction(orderData));
   return result;
}).then(
   value => {
     console.log(value);
  },
   err => {
     console.error(err.stack);
  }
);

위와 같이 yield put(createTransaction) 으로 실행해 주었다.

여기서 co 라는 라이브러리가 사용되었는데, yield같은 generator 함수의 return 값이 promise일때 처리해주는 npm 이다. 그리고 참고로 ReactGA가 설치되어 있다는 가정하에 진행을 하였다.
|참고
아래의 크롬 확장 프로그램들을 설치하면, google analytics관련 이벤트들이 어떻게 실행되는지 한눈에 확인이 가능하다. e-commerce 데이터들이 잘들어오는지 real-time으로 확인이 불가하기 때문에 아래 확장 프로그램설치는 필수다 : (
Google Analytics DebuggerTag Assistant (by Google)



참고: http://derpturkey.com/react-redux-service-for-google-analytics-tracking/



'Front end > React' 카테고리의 다른 글

React - 네이버 맵 api 활용하기  (0) 2018.05.12
React -redux thunk, redux saga  (0) 2018.03.07
React - 리덕스 미들웨어  (0) 2018.03.02
Redux- 리덕스 총정리하기  (0) 2018.03.02
React-google analytics 달기  (0) 2018.02.26
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
TAG
more
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함