跳到主要内容

6 篇博文 含有标签「react」

查看所有标签

财经今日 开源了:界面、它读的库表结构,以及中间的 API

· 阅读需 8 分钟
财经今日 · CaiJing Today财经今日 · CaiJing Today

一个交易日,是六个标签页​

九点二十五,集合竞价结束。九点半,开盘。从这一刻起,接下来四个小时, 市场一直在说话:一次公开市场操作、一个期货点位、一个指数点位、一份征求意见 稿、一份公司公告,再加上一篇分析——而这两者到底差在哪。

这些消息都是真的,也都真实存在。只是它们不在同一个地方。

于是你打开六个标签页:行情快讯、指数页面、板块热力图、日历、公告检索、还有 一个论坛。它们各自的版式、配色、关注点都不一样,而且大多是为别人的问题而 做的。

CaiJing Today is open source — the board, the schema it reads, and the API in between

· 阅读需 9 分钟
CaiJing Today · 财经今日CaiJing Today · 财经今日

A market day is a lot of tabs​

At 09:25 the call auction ends. At 09:30 the tape starts, and for the next four hours the Chinese market talks continuously — a central-bank operation, a futures point, an index level, a draft regulation, a company filing, an analyst note about the difference between two of them.

All of it is real, and all of it is somewhere. But it is not in the same place.

So you end up with six tabs open — a wire service, a quote page, a sector heatmap, a calendar, a filing index, a forum — and the tab bar quietly becomes the product. Every one of them is a different layout, a different colour scheme, a different idea of what matters, and most of them are built for somebody else's question.

whereq.com 开源了:地图、爬虫,以及它读到的所有数据

· 阅读需 8 分钟
whereq.comwhereq.com

一枚图钉,其实只是一句很小的话​

站在多伦多的一条街上,看着眼前这个门牌号,地图只会告诉你一句话:这里有一枚图钉。一家咖啡馆,一间医院,一所学校,也许还有一个停车场。

但一个地方本身是一大堆话,而图钉是其中最不重要的那句。

这个地址属于哪个学区 catchment?走路能到图书馆吗,是哪一家?街角加油站今天收 1.42 还是 1.79?这栋楼落在 ward 里、neighbourhood 里,还是两者都算?上周这条街上出过什么事?

whereq.com is open source — the map, the crawler, and everything it reads

· 阅读需 8 分钟
whereq.comwhereq.com

A pin is a very small sentence​

Stand on a street in Toronto and look at the address in front of you. A map gives you one claim about it: there is a pin here. A coffee shop. A hospital. A school. Maybe a parking garage.

But the place itself is a pile of claims, and the pin is the least interesting one of them.

Which school catchment is that address in? Can I walk to a library, and which one? Is the fuel station on the corner charging 1.42or1.42 or 1.79? Is that building inside a ward, or inside a neighbourhood, or in a ward and a neighbourhood? Did anything happen on this street last week?

Resolving Dependency Issues in useEffect for a React Application

· 阅读需 6 分钟

Last week, I was tasked with building a Parameters.tsx component, and let me tell you, the struggle was real! I got completely entangled in a web of useEffect dependencies. It was like trying to untangle a Christmas tree of wires! 🎄 But hey, I finally emerged victorious (mostly) and learned some valuable lessons along the way. Here's the story...

The Product Requirement​

  1. Initializes a table with passed-in parameters (Record<string, string>).
  2. Allows in-place editing of table rows.
  3. Automatically persists updated parameters to local storage, using a passed-in URL as the key.

Implementation​

The implementation involves two useEffect hooks:

  1. First useEffect: Loads the passed-in parameters into the table.
  2. Second useEffect: Saves the updated parameters to local storage whenever the user makes changes to the table rows.

The Problem​

The key issue arises from the second useEffect. Since the URL (used as the storage key) is passed into the component, it was added as a dependency. This caused unintended behavior when switching endpoints, leading to:

  • Saving the parameters of a previous endpoint under the new endpoint's URL.

Scenario Details​

When switching endpoints, the restfulEndpointUrl (passed-in URL) changes. Since the URL is used as the key for saving parameters to local storage, it was added as a dependency to the second useEffect. However, this led to incorrect behavior:

  • When the URL changes, the useEffect is triggered.
  • At this point, the table still contains the parameters of the previous endpoint.
  • As a result, the parameters of the previous endpoint are saved under the new endpoint’s URL, which is incorrect.

Why This Happens​

The useEffect hook runs whenever any of its dependencies change. By including restfulEndpointUrl in the dependency array, the useEffect is triggered when the URL changes, even though the table content hasn’t been updated yet.


Root Cause: Unnecessary Dependencies in useEffect​

Let’s break down why adding restfulEndpointUrl as a dependency caused the issue:

  1. How useEffect Dependencies Work
    The dependencies in the useEffect array dictate when the hook is re-triggered. By including restfulEndpointUrl, the persistence logic was unnecessarily invoked whenever the URL changed.

  2. Incorrect State Handling
    When the URL changed, the persistence logic was triggered prematurely, using the outdated state of rows, leading to data being saved under the incorrect key.

Impact of This Bug​

Here’s a sequence of events that led to the bug:

1. restfulEndpointUrl = "endpoint_1"
- Rows initialized and saved correctly under "endpoint_1".
2. restfulEndpointUrl changes to "endpoint_2"
- useEffect triggers immediately.
- Old rows (from "endpoint_1") are saved under "endpoint_2".
3. User edits table.
- New rows are saved under "endpoint_2", but previous data is corrupted.

Solution: Leveraging useRef​

To fix this, we need to ensure that the persistence logic only runs when rows changes, and not when the URL changes. This can be achieved by:

  1. Removing restfulEndpointUrl from the dependency array of the useEffect that handles persistence.
  2. Using a useRef to always access the latest URL without triggering the useEffect.

The useRef hook provides a solution by holding a mutable reference to the latest URL without triggering re-renders or re-triggering the useEffect. Here’s why it works:

  • Avoiding Dependencies: By using useRef, we avoid adding restfulEndpointUrl to the dependency array. The persistence logic is now triggered only when rows change.
  • Always Up-to-Date: Updating the useRef in its own useEffect ensures it always holds the latest URL.

Why useRef Fixes the Problem​

The useRef hook allows us to store a mutable value that persists across renders without causing re-renders. By storing the URL in a ref, we can:

  • Access the latest URL value without adding it as a dependency to useEffect.
  • Ensure that the persistence logic only runs when rows changes, avoiding incorrect saves.

Code Comparison​

Before Fixing​

const [rows, setRows] = useState<Row[]>([]);

// Initialize rows
useEffect(() => {
const initialRows = Object.entries(initialParams).map(([key, value]) => ({
selected: true,
key,
value,
description: "",
}));
setRows(initialRows);
}, [initialParams]);

// Persist changes
useEffect(() => {
if (restfulEndpointUrl) {
const params = rows
.filter((row) => row.selected && row.key)
.reduce((acc, row) => {
acc[row.key] = row.value;
return acc;
}, {});

LocalStorageHelper.setParams(restfulEndpointUrl, params);
}
}, [rows, restfulEndpointUrl]); // restfulEndpointUrl as a dependency causes issues

After Fixing​

const [rows, setRows] = useState<Row[]>([]);
const restfulEndpointUrlRef = useRef(restfulEndpointUrl);

// Update ref when URL changes
useEffect(() => {
restfulEndpointUrlRef.current = restfulEndpointUrl;
}, [restfulEndpointUrl]);

// Initialize rows
useEffect(() => {
const initialRows = Object.entries(initialParams).map(([key, value]) => ({
selected: true,
key,
value,
description: "",
}));
setRows(initialRows);
}, [initialParams]);

// Persist changes
useEffect(() => {
const params = rows
.filter((row) => row.selected && row.key)
.reduce((acc, row) => {
acc[row.key] = row.value;
return acc;
}, {});

LocalStorageHelper.setParams(restfulEndpointUrlRef.current, params);
}, [rows]); // URL dependency removed

Sequence Diagram: Before the Fix​

sequenceDiagram
participant User
participant Component
participant LocalStorage

User->>Component: Switches Endpoint
Component->>Component: restfulEndpointUrl changes
Component->>Component: useEffect (persistence) triggers
Component->>Component: Table still contains params of previous endpoint
Component->>LocalStorage: Incorrect params saved under new endpoint's URL

Explanation​

  1. The user switches the endpoint.
  2. The restfulEndpointUrl changes.
  3. The useEffect (persistence) triggers because restfulEndpointUrl is a dependency.
  4. The table still contains the parameters of the previous endpoint.
  5. The incorrect parameters are saved under the new endpoint’s URL.

Sequence Diagram: After the Fix​

sequenceDiagram
participant User
participant Component
participant LocalStorage

User->>Component: Switches Endpoint
Component->>Component: restfulEndpointUrl changes
Component->>Component: ref updated with new URL
Component->>Component: Table updated with new endpoint's params
User->>Component: Edits Table
Component->>Component: useEffect (persistence) triggers
Component->>LocalStorage: Correct params saved under new endpoint's URL

Explanation​

  1. The user switches the endpoint.
  2. The restfulEndpointUrl changes.
  3. The ref is updated with the new URL.
  4. The table is updated with the new endpoint’s parameters.
  5. The user edits the table.
  6. The useEffect (persistence) triggers because rows changed.
  7. The correct parameters are saved under the new endpoint’s URL.

Key Differences in the Diagrams​

Before the FixAfter the Fix
useEffect triggers when restfulEndpointUrl changes.useEffect triggers only when rows changes.
Incorrect parameters are saved because the table hasn’t been updated yet.Correct parameters are saved because the table is updated before persistence.
restfulEndpointUrl is a dependency in useEffect.restfulEndpointUrl is stored in a ref and not a dependency in useEffect.


Key Takeaways​

Why Unnecessary Dependencies Are Problematic​

  1. They can cause re-triggers in useEffect that don’t align with the intended logic.
  2. This often leads to outdated or incorrect state usage.

Why useRef Is the Solution​

  1. useRef provides a mutable container that doesn’t cause re-renders or hook re-triggers.
  2. It allows us to maintain the latest value of a variable without adding it to useEffect dependencies.

Conclusion​

Using useEffect effectively requires careful consideration of its dependencies. In this case, leveraging useRef eliminated unnecessary triggers, ensuring the correct behavior when switching endpoints. This approach is a best practice for similar scenarios where state changes need to be decoupled from unrelated external variables.

Deep Dive into Local Storage Usage in React with TypeScript

· 阅读需 4 分钟

Local storage is a simple yet powerful tool for persisting data in web applications. In this article, we'll explore every detail of local storage usage in React with TypeScript, including best practices, sample code, and test cases. The illustrations are based on the latest versions of React (18.x) and TypeScript (5.x).


What is Local Storage?​

Local storage is a web API that allows developers to store key-value pairs in a web browser. The data persists even after the browser is closed, making it ideal for saving user preferences, authentication tokens, and other non-sensitive data.

Key Characteristics of Local Storage:​

  • Synchronous API: Operations are blocking.
  • Storage Limit: Approximately 5MB per domain.
  • Data Lifetime: Persists until explicitly deleted.
  • Data Scope: Accessible only within the same origin.

Using Local Storage in React with TypeScript​

1. Basic CRUD Operations​

Local storage provides three core methods:

  • localStorage.setItem(key, value)
  • localStorage.getItem(key)
  • localStorage.removeItem(key)

Example: Wrapper Utility for Local Storage​

We can create a type-safe utility to handle common operations:

// utils/localStorage.ts
export class LocalStorageHelper {
static setItem<T>(key: string, value: T): void {
localStorage.setItem(key, JSON.stringify(value));
}

static getItem<T>(key: string): T | null {
const value = localStorage.getItem(key);
return value ? JSON.parse(value) as T : null;
}

static removeItem(key: string): void {
localStorage.removeItem(key);
}
}

Test Cases​

Using Jest, we can write unit tests to validate the utility:

// utils/localStorage.test.ts
import { LocalStorageHelper } from "./localStorage";

describe("LocalStorageHelper", () => {
beforeEach(() => {
localStorage.clear();
});

it("should set and retrieve an item", () => {
LocalStorageHelper.setItem("key", { name: "John" });
const item = LocalStorageHelper.getItem<{ name: string }>("key");
expect(item).toEqual({ name: "John" });
});

it("should return null for non-existent keys", () => {
const item = LocalStorageHelper.getItem("nonexistent");
expect(item).toBeNull();
});

it("should remove an item", () => {
LocalStorageHelper.setItem("key", "value");
LocalStorageHelper.removeItem("key");
const item = LocalStorageHelper.getItem("key");
expect(item).toBeNull();
});
});

2. Integrating Local Storage in React Components​

Example: Using Local Storage with useState​

// components/Counter.tsx
import React, { useState, useEffect } from "react";
import { LocalStorageHelper } from "../utils/localStorage";

const Counter: React.FC = () => {
const [count, setCount] = useState<number>(() => {
return LocalStorageHelper.getItem<number>("count") || 0;
});

useEffect(() => {
LocalStorageHelper.setItem("count", count);
}, [count]);

return (
<div>
<h1>Counter: {count}</h1>
<button onClick={() => setCount((prev) => prev + 1)}>Increment</button>
<button onClick={() => setCount((prev) => prev - 1)}>Decrement</button>
</div>
);
};

export default Counter;

Test Cases​

// components/Counter.test.tsx
import React from "react";
import { render, screen, fireEvent } from "@testing-library/react";
import Counter from "./Counter";

describe("Counter Component", () => {
it("should initialize with value from local storage", () => {
localStorage.setItem("count", "5");
render(<Counter />);
expect(screen.getByText(/Counter: 5/i)).toBeInTheDocument();
});

it("should increment the counter", () => {
render(<Counter />);
fireEvent.click(screen.getByText(/Increment/i));
expect(screen.getByText(/Counter: 1/i)).toBeInTheDocument();
});

it("should decrement the counter", () => {
render(<Counter />);
fireEvent.click(screen.getByText(/Decrement/i));
expect(screen.getByText(/Counter: -1/i)).toBeInTheDocument();
});
});

3. React Hooks for Local Storage​

We can create a custom hook to encapsulate the logic for interacting with local storage.

Example: Custom Hook​

// hooks/useLocalStorage.ts
import { useState } from "react";

function useLocalStorage<T>(key: string, initialValue: T) {
const [storedValue, setStoredValue] = useState<T>(() => {
try {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.error("Error reading localStorage key", key, error);
return initialValue;
}
});

const setValue = (value: T) => {
try {
setStoredValue(value);
localStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.error("Error setting localStorage key", key, error);
}
};

return [storedValue, setValue] as const;
}

export default useLocalStorage;

Usage Example​

// components/ThemeSwitcher.tsx
import React from "react";
import useLocalStorage from "../hooks/useLocalStorage";

const ThemeSwitcher: React.FC = () => {
const [theme, setTheme] = useLocalStorage<string>("theme", "light");

return (
<div className={`theme-${theme}`}>
<h1>Current Theme: {theme}</h1>
<button onClick={() => setTheme("light")}>Light</button>
<button onClick={() => setTheme("dark")}>Dark</button>
</div>
);
};

export default ThemeSwitcher;

4. Best Practices for Local Storage in React​

  1. Avoid Storing Sensitive Data: Local storage is not secure; avoid storing sensitive information like passwords or tokens.
  2. Validate Stored Data: Always validate and sanitize data retrieved from local storage.
  3. Error Handling: Wrap local storage operations in try-catch blocks to handle potential errors.
  4. Abstract Logic: Use utilities or hooks to encapsulate local storage interactions for reusability and type safety.
  5. Synchronize Across Tabs: Use the storage event to synchronize data across multiple tabs.

Example: Tab Synchronization​

// hooks/useSyncLocalStorage.ts
import { useEffect } from "react";

export function useSyncLocalStorage(key: string, callback: (newValue: string | null) => void) {
useEffect(() => {
const handler = (event: StorageEvent) => {
if (event.key === key) {
callback(event.newValue);
}
};

window.addEventListener("storage", handler);
return () => window.removeEventListener("storage", handler);
}, [key, callback]);
}