2021年6月26日 星期六

讀 Vue3 Composition API 筆記 1

 一個用來處理組件共用狀態與邏輯的功能,是前端在工作時必備的,例如登入後要把登入狀態跟一些環境變數給予大部分的組件,或開發新的功能要在多個平行組件上運作,如果一層一層傳遞一是麻煩,二是要改 Code 追蹤的時候很痛苦,在 React 是使用 Context 或 Redux ,Vue 是 Vuex,原理都是創建一個 Store ,Store 儲存 State 與 Dispatch,例如登入與否,State:{ isLogin: false },Dispatch 就會是一個更新 State 的 function,如 dispatch({ type:isLogin , data:true}),再透過 reducer 去更新 State 使狀態發生改變,意義在於使共用狀態與邏輯是可追蹤的,方便知道哪些組件會更改,以及除錯會比較方便。

在 Vue 3 中,綁定需要加上 ref ,例如: const isLogin = ref ( false ) ,因為原始型別與物件型別在傳值與傳參考的反應不同。Vue 2 升級 Vue 3 時,生命週期可以由 vue import,mount 改成 onMounted,watch(觀察對象, callback , option),剩下的下集再續。

setup () {

   const isLogin = ref ( false )

   onMounted(()=>{

     dispatch()

})

}


參考資料:

Vue3文件 

Kuro 在大神來六角的解說

2021年6月20日 星期日

React 實作第三方登入:Google

     前陣子因為工作串接 Google reCAPTCHA Enterprise ,為了測試有辦了 Google 的雲端服務,現在買東西登入也懶得打一堆有得沒得,相當欣賞這種一個按鈕就解決的登入方式,所以來實作看看。

首先看文件引入 <script src="https://accounts.google.com/gsi/client" async defer></script> 

在 Next.js 用 GCP 相關服務都有點麻煩,剛好看到有套件就用了

npm install react-google-login 

再來設定 GCP OAuth 相關

在 GCP 左邊 API 與服務 選擇 OAuth 同意畫面進行設置,測試時記得加上 localhost ,上正式或測試環境時也要加上 domain。

API 與服務 > 憑證 建立憑證,建立OAuth 用戶端 ID,授權的 JavaScript 來源也要加上包含 localhost 等 domain ,重新導向 URI 是登入成功之後會導轉的頁面,然後可以把 JSON 下載下來可以看到 client_id ,需要設置在登入登出按鈕的組件上。

最後就運用 Next.js 完成設定與部屬。




取得的個資會在 profileObj 裡,進行 Hook 設置跟登入導轉(也可以直接寫在 GCP 的重新導向URI)


其他有練習使用 Tailwind CSS 建立 Context 部屬 Vercel。

Github: https://github.com/oneraner/react 原始碼

Vercel: https://react-delta-bay.vercel.app/ Demo位置



參考資料: 






2021年6月9日 星期三

非同步處理 async await array

 故事是這樣的,有很多小錢包需要分別打 API 去取得餘額,GraphQL API 本身是非同步的,可是當我要加總所有錢包的餘額就會:

const total = async () => {

const walletList = [ a , b , c , d , e]

let total = 0

await walletList.forEach( async  (item,index) => {

    const cash = await getCashApi(item)

     total = total += cash

     console.log(index)

})

console.log(total)

}

然後 index 亂跳 total = 0,完全沒用。


原因是 await 只看後面回傳的是不是 Promise ,但在改寫之前還要釐清是否有順序問題,如果要照順序,就用 reduce 的方法寫,不過我只要算加總,錢包 API 的錢回來的順序不重要,因此可以用 Promise.all 改寫:

const total = async () => {

const walletList = [ a , b , c , d , e]

let total = 0

await Promise.all(walletList.map( async  (item,index) => {

    const cash = await getCashApi(item)

    const outputCash = cash === undefined ?  0  :  cash   //後來發現 API 會回傳 undefined 導致加不起來

     total = total += outputCash

     console.log(index)

}))

console.log(total)

}

這樣就會出來正確的 total 啦



參考資料: