Skip to content

Commit

Permalink
feat: support ssr
Browse files Browse the repository at this point in the history
  • Loading branch information
yqrashawn committed Sep 18, 2021
1 parent 66cb999 commit ff19cb4
Show file tree
Hide file tree
Showing 13 changed files with 10,256 additions and 189 deletions.
30 changes: 30 additions & 0 deletions .github/workflows/ssr-test.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
name: SSR Check

on: [push]

jobs:
check:
runs-on: ubuntu-20.04
strategy:
matrix:
node-version: [16.5]
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn config get cacheFolder)"
- uses: actions/cache@v2
id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-and-maven-cache.outputs.cache-hit != 'true'`)
with:
path: |
${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- run: yarn install --immutable
- run: yarn --cwd ./test/gatsby/ install
- run: yarn --cwd ./test/gatsby/ build
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
/node_modules/
/storybook-static/
/lib/
/test/gatsby/node_modules
/test/gatsby/public
15 changes: 15 additions & 0 deletions src/ssr-helper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export function isSSR() {
return typeof globalThis.window?.document?.createElement === "undefined"
}

export function isBrowser() {
return !isSSR()
}

export function onSSR(callback, otherwise) {
return isSSR() ? callback() : otherwise?.()
}

export function onBrowser(callback, otherwise) {
return isBrowser() ? callback() : otherwise?.()
}
61 changes: 36 additions & 25 deletions src/useBalance.js
Original file line number Diff line number Diff line change
@@ -1,40 +1,51 @@
import SINGLE_CALL_BALANCES_ABI from "./contracts/cfx-single-call-balance-checker-abi.json";
import { useEffect } from "react";
import { useConfluxJSDefined, useEpochNumberSWR } from "./";
import { useChainNetId } from './';
import initContract from "./initContract";
import SINGLE_CALL_BALANCES_ABI from "./contracts/cfx-single-call-balance-checker-abi.json"
import { useEffect } from "react"
import { useConfluxJSDefined, useEpochNumberSWR } from "./"
import { useChainNetId } from "./"
import initContract from "./initContract"
import { onBrowser } from "./ssr-helper.js"

export const UPDATE_USER_BALANCE_SWR_ID = "UPDATE_USER_BALANCE_SWR_ID";
export const UPDATE_USER_BALANCE_SWR_ID = "UPDATE_USER_BALANCE_SWR_ID"

let c = initContract({
abi: SINGLE_CALL_BALANCES_ABI,
address: "0x8f35930629fce5b5cf4cd762e71006045bfeb24d",
}, window?.confluxJS);
let c = onBrowser(
() =>
initContract(
{
abi: SINGLE_CALL_BALANCES_ABI,
address: "0x8f35930629fce5b5cf4cd762e71006045bfeb24d",
},
window?.confluxJS
),
() => null
)

function getTokensBalance(userAddr, tokenAddrs) {
return c
?.balances(
[userAddr],
["0x0000000000000000000000000000000000000000", ...tokenAddrs]
)
?.call();
?.balances(
[userAddr],
["0x0000000000000000000000000000000000000000", ...tokenAddrs]
)
?.call()
}

export default function useBalance(userAddr, tokenAddrs) {
const confluxJSDefined = useConfluxJSDefined();
const {chainId} = useChainNetId()
const confluxJSDefined = useConfluxJSDefined()
const { chainId } = useChainNetId()

useEffect(() => {
if (!confluxJSDefined || !chainId) return
if (c) {
c._feedAddressNetId(SINGLE_CALL_BALANCES_ABI, window.confluxJS)
} else {
c = initContract({
abi: SINGLE_CALL_BALANCES_ABI,
address: "0x8f35930629fce5b5cf4cd762e71006045bfeb24d",
}, window.confluxJS);
c = initContract(
{
abi: SINGLE_CALL_BALANCES_ABI,
address: "0x8f35930629fce5b5cf4cd762e71006045bfeb24d",
},
window.confluxJS
)
}
}, [confluxJSDefined, Boolean(chainId)]);
}, [confluxJSDefined, Boolean(chainId)])

const {
data: [balance, ...tokenBalances],
Expand All @@ -46,9 +57,9 @@ export default function useBalance(userAddr, tokenAddrs) {
: null,
() => getTokensBalance(userAddr, tokenAddrs),
{ initialData: [0, ...tokenAddrs.map(() => 0)], revalidateOnMount: true }
);
)

if (balanceErr) console.error(`Get Balance Error: ${balanceErr.message}`);
if (balanceErr) console.error(`Get Balance Error: ${balanceErr.message}`)

return [balance, tokenBalances, isValidating];
return [balance, tokenBalances, isValidating]
}
59 changes: 34 additions & 25 deletions src/useChainNetId.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,39 @@
import { useConfluxJSDefined } from "./";
import { useEffectOnce } from "react-use";
import { useState } from "react";
import { useConfluxJSDefined } from "./"
import { useEffectOnce } from "react-use"
import { useState } from "react"
import { onBrowser } from "./ssr-helper.js"

export const UPDATE_CHAINID_SWR_ID = "UPDATE_CHAINID_SWR_ID";
export const UPDATE_NETWORKID_SWR_ID = "UPDATE_NETWORKID_SWR_ID";
export const UPDATE_CHAINID_SWR_ID = "UPDATE_CHAINID_SWR_ID"
export const UPDATE_NETWORKID_SWR_ID = "UPDATE_NETWORKID_SWR_ID"

export default function useChainNetId() {
useConfluxJSDefined();
export default () =>
onBrowser(
() => {
useConfluxJSDefined()

const [chainId, setChainId] = useState(window?.conflux?.chainId);
const [networkId, setNetworkId] = useState(parseInt(window?.conflux?.networkVersion ,10) || null);
const [chainId, setChainId] = useState(
globalThis.window?.conflux?.chainId
)
const [networkId, setNetworkId] = useState(
parseInt(window?.conflux?.networkVersion, 10) || null
)

useEffectOnce(() => {
const chainListener = (chainId) => {
setChainId(chainId);
};
const networkListener = (networkId) => {
setNetworkId(parseInt(networkId, 10) || null);
};
window?.conflux?.on("chainIdChanged", chainListener);
window?.conflux?.on("networkChanged", networkListener);
return () => {
window?.conflux?.off("chainIdChanged", chainListener);
window?.conflux?.off("networkChanged", networkListener);
};
})
useEffectOnce(() => {
const chainListener = (chainId) => {
setChainId(chainId)
}
const networkListener = (networkId) => {
setNetworkId(parseInt(networkId, 10) || null)
}
window?.conflux?.on("chainIdChanged", chainListener)
window?.conflux?.on("networkChanged", networkListener)
return () => {
window?.conflux?.off("chainIdChanged", chainListener)
window?.conflux?.off("networkChanged", networkListener)
}
})

return {chainId, networkId}
}
return { chainId, networkId }
},
() => ({})
)
49 changes: 27 additions & 22 deletions src/useConfluxJSDefined.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,32 @@
import { useState, useRef } from "react";
import { useEffectOnce } from "react-use";
import { useState, useRef } from "react"
import { useEffectOnce } from "react-use"
import { onBrowser } from "./ssr-helper.js"

let CONFLUXJS_INTERVAL_DEFINED = false;
let CONFLUXJS_INTERVAL_DEFINED = false

export default function useConfluxJSDefined(customInterval = 100) {
const [defined, setDefined] = useState(
CONFLUXJS_INTERVAL_DEFINED || Boolean(window?.confluxJS)
);
const intervalRef = useRef(null);
useEffectOnce(() => {
if (!defined) {
intervalRef.current = setInterval(() => {
if (window?.confluxJS) {
setDefined(true);
clearInterval(intervalRef.current);
export default (customInterval = 100) =>
onBrowser(
() => {
const [defined, setDefined] = useState(
CONFLUXJS_INTERVAL_DEFINED || Boolean(window?.confluxJS)
)
const intervalRef = useRef(null)
useEffectOnce(() => {
if (!defined) {
intervalRef.current = setInterval(() => {
if (window?.confluxJS) {
setDefined(true)
clearInterval(intervalRef.current)
}
}, customInterval)
}
}, customInterval);
}

return () => {
if (intervalRef.current) clearInterval(intervalRef.current);
};
});
return () => {
if (intervalRef.current) clearInterval(intervalRef.current)
}
})

return defined;
}
return defined
},
() => false
)
Loading

0 comments on commit ff19cb4

Please sign in to comment.