avoid loading the same block multiple times

This commit is contained in:
Andrea Franz 2020-02-27 17:59:19 +01:00
parent bff3e635a3
commit 05727e7c90
No known key found for this signature in database
GPG Key ID: 4F0D2F2D9DE7F29D
3 changed files with 40 additions and 4 deletions

View File

@ -1,5 +1,12 @@
import { Dispatch } from 'redux';
import { config } from '../global';
import { RootState } from '../reducers';
export const BLOCK_LOADING = "BLOCK_LOADING";
export interface BlockLoadingAction {
type: typeof BLOCK_LOADING
number: number
}
export const BLOCK_LOADED = "BLOCK_LOADED";
export interface BlockLoadedAction {
@ -9,6 +16,7 @@ export interface BlockLoadedAction {
}
export type BlocksActions =
BlockLoadingAction |
BlockLoadedAction;
export const blockLoaded = (number: number, timestamp: number): BlockLoadedAction => ({
@ -17,8 +25,20 @@ export const blockLoaded = (number: number, timestamp: number): BlockLoadedActio
timestamp,
});
export const loadingBlock = (number: number): BlockLoadingAction => ({
type: BLOCK_LOADING,
number,
});
export const loadBlock = (number: number) => {
return (dispatch: Dispatch) => {
return (dispatch: Dispatch, getState: () => RootState) => {
if (getState().blocks[number] !== undefined) {
// block already loaded
return;
}
dispatch(loadingBlock(number))
config.web3!.eth.getBlock(number).then(b => {
let timestamp;
if (typeof b.timestamp === "string") {

View File

@ -115,7 +115,7 @@ const TransactionsListItem = (props: Props) => {
</span>;
const secondary = <span>
<span className={classes.block}>from: {fromAddress}</span>
<span className={classes.block}>{tx.blockNumber} from: {fromAddress}</span>
<span className={classes.block}>to: {toAddress}</span>
</span>;

View File

@ -1,11 +1,12 @@
import {
BLOCK_LOADING,
BLOCK_LOADED,
BlocksActions,
} from '../actions/blocks';
export interface BlockState {
number: number
timestamp: number
timestamp: number | undefined
}
export interface BlocksState {
@ -16,11 +17,26 @@ const initialState = {};
export const blocksReducer = (state: BlocksState = initialState, action: BlocksActions): BlocksState => {
switch (action.type) {
case BLOCK_LOADED: {
case BLOCK_LOADING: {
return {
...state,
[action.number]: {
number: action.number,
timestamp: undefined,
}
}
}
case BLOCK_LOADED: {
const blockState = state[action.number];
if (blockState === undefined) {
return state;
}
return {
...state,
[action.number]: {
...blockState,
timestamp: action.timestamp,
}
}