mirror of
https://github.com/DayuanJiang/next-ai-draw-io.git
synced 2026-01-02 22:32:27 +08:00
fix: use ref for chartXML to avoid stale closure in onToolCall
The onToolCall callback was capturing stale chartXML value due to JavaScript closure. Using a ref ensures we always get the latest value.
This commit is contained in:
@@ -68,6 +68,12 @@ export default function ChatPanel({
|
|||||||
// Store XML snapshots for each user message (keyed by message index)
|
// Store XML snapshots for each user message (keyed by message index)
|
||||||
const xmlSnapshotsRef = useRef<Map<number, string>>(new Map());
|
const xmlSnapshotsRef = useRef<Map<number, string>>(new Map());
|
||||||
|
|
||||||
|
// Ref to track latest chartXML for use in callbacks (avoids stale closure)
|
||||||
|
const chartXMLRef = useRef(chartXML);
|
||||||
|
useEffect(() => {
|
||||||
|
chartXMLRef.current = chartXML;
|
||||||
|
}, [chartXML]);
|
||||||
|
|
||||||
const { messages, sendMessage, addToolResult, status, error, setMessages } =
|
const { messages, sendMessage, addToolResult, status, error, setMessages } =
|
||||||
useChat({
|
useChat({
|
||||||
transport: new DefaultChatTransport({
|
transport: new DefaultChatTransport({
|
||||||
@@ -100,10 +106,12 @@ export default function ChatPanel({
|
|||||||
let currentXml = "";
|
let currentXml = "";
|
||||||
try {
|
try {
|
||||||
console.log("[edit_diagram] Starting...");
|
console.log("[edit_diagram] Starting...");
|
||||||
// Use chartXML from context directly - more reliable than export
|
// Use chartXML from ref directly - more reliable than export
|
||||||
// especially on Vercel where DrawIO iframe may have latency issues
|
// especially on Vercel where DrawIO iframe may have latency issues
|
||||||
if (chartXML) {
|
// Using ref to avoid stale closure in callback
|
||||||
currentXml = chartXML;
|
const cachedXML = chartXMLRef.current;
|
||||||
|
if (cachedXML) {
|
||||||
|
currentXml = cachedXML;
|
||||||
console.log("[edit_diagram] Using cached chartXML, length:", currentXml.length);
|
console.log("[edit_diagram] Using cached chartXML, length:", currentXml.length);
|
||||||
} else {
|
} else {
|
||||||
// Fallback to export only if no cached XML
|
// Fallback to export only if no cached XML
|
||||||
|
|||||||
Reference in New Issue
Block a user