Explore // src/pages/StockVista/StockVista.js import React, { useEffect, useState, useCallback }… Save Share Download ▾ Report// src/pages/StockVista/StockVista.js
import React, { useEffect, useState, useCallback } from 'react';
import { useWebSocket } from '../../services/websocketContext';
import { requestFilteredData, requestStockData } from "../../api/stockVistaRequests";
import {
Container, Typography, CircularProgress, Grid, Box,
IconButton, Tooltip, Paper, Tabs, Tab
} from "@mui/material";
import RefreshIcon from '@mui/icons-material/Refresh';
import Filters from './Filters';
import GraphsTabContent from './tabs/GraphsTabContent';
import DataTabContent from './tabs/DataTabContent';
import AnalyticsTabContent from './tabs/AnalyticsTabContent';
import StackedLongShortAreaChart from './StackedAreaChart';
import "./StockVista.css"
function StockVista() {
// Add state for tab control
const [activeTab, setActiveTab] = useState(0);
const { websocketService, isConnected } = useWebSocket();
const [filteredData, setFilteredData] = useState(null);
const [stockData, setStockdData] = useState(null);
const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(10);
const [filters, setFilters] = useState({
Country: null,
type: null,
customer: null,
status: null,
Tenor: null,
scope: null,
product: null,
});
const [filterOptions, setFilterOptions] = useState({
Country: [],
type: [],
customer: [],
status: [],
Tenor: [],
scope: [],
product: ['REV', 'REPO'],
});
const [filtersExpanded, setFiltersExpanded] = useState(true);
const handleTabChange = (event, newValue) => {
setActiveTab(newValue);
};
const formatDate = (dateObj) => {
if (!dateObj) return '';
try {
console.log('Date object to format:', dateObj, 'Type:', typeof dateObj);
let timestamp;
if (dateObj.date) {
if (typeof dateObj. date === 'number') {
timestamp = dateObj.date;
} else if (typeof dateObj. date === 'string') {
timestamp = new Date(dateObj.date).getTime();
} else if (dateObj. date.numberLong) {
timestamp = parseInt(dateObj. date.$numberLong);
} else {
console.log('Unknown MongoDB date format', dateObj);
return String(dateObj);
}
} else if (typeof dateObj === 'string') {
timestamp = new Date(dateObj).getTime();
} else if (dateObj instanceof Date) {
timestamp = dateObj.getTime();
} else {
console.log('Unhandled date format', dateObj);
return String(dateObj);
}
Show full message · 327 lines AssistantCopy response
Copy first prompt
Other models, same or similar prompt Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Details
Provider unknown
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Added to archive Nov 26, 2026
ID 01m8artxm88prxzv8n50941xgvSource & license Imported from Search Arena v1 (7K preferences) (source ). Imported records earn no Research Points.
Upstream record: data/search-arena-v1-preference-7k.parquet:3547:a
lmarena-ai/search-arena-v1-7k, revision 06865038ceb415c1942e58bff8f14150cbc9fbcd
License: CC-BY-4.0 (prompts); model outputs under provider terms
Dataset releases Not yet included in a published release.
if (isNaN(timestamp)) {
console.log('Invalid timestamp', timestamp, 'from', dateObj);
return String(dateObj);
}
const date = new Date(timestamp);
const day = date.getDate().toString().padStart(2, '0');
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const year = date.getFullYear();
const formattedDate = `${day}/${month}/${year}`;
console.log('Formatted date:', formattedDate, 'from', dateObj);
return formattedDate;
} catch (e) {
console.error("Error formatting date:", e, dateObj);
return String(dateObj);
}
const columns = [
{ id: 'date', label: 'Date', minWidth: 100,format: formatDate },
{ id: 'dateStart', label: 'Date début', minWidth: 100, format: formatDate },
{ id: 'dateStop', label: 'Date fin', minWidth: 100, format: formatDate },
{ id: 'customer', label: 'Client', minWidth: 100 },
{ id: 'type', label: 'Type de client', minWidth: 120 },
{ id: 'Country', label: 'Pays', minWidth: 50 },
{ id: 'status', label: 'Statut', minWidth: 50 },
{ id: 'Tenor', label: 'Maturité', minWidth: 50 },
{ id: 'Bond', label: 'Bond', minWidth: 120 },
{ id: 'qtyVerb', label: 'Quantité', minWidth: 70, align: 'right'},
{ id: 'customerRFQValue', label: 'Valeur', minWidth: 70, align: 'right' },
{ id: 'dealDuration', label: 'Durée', minWidth: 70, align: 'right' },
];
const fetchFilteredData = useCallback((appliedFilters) => {
if (isConnected) {
requestFilteredData(appliedFilters);
}
}, [isConnected]);
const fetchStockData = useCallback((appliedFilters) => {
if (isConnected) {
requestStockData(appliedFilters);
}
}, [isConnected]);
const processData = useCallback((data) => {
if (!data || !Array.isArray(data)) return [];
code Copy code
return data.map(item => ({
...item,
date: formatDate(item?.date),
dateStart: formatDate(item?.dateStart),
dateStop: formatDate(item?.dateStop),
// Ensure all required fields have values
Country: item?.Country || '',
type: item?.type || '',
customer: item?.customer || '',
status: item?.status || '',
Tenor: item?.Tenor || '',
// Add other fields with default values as needed
}));
useEffect(() => {
if (!isConnected) return;
code Copy code
const unsubscribe = websocketService.subscribe('stock_vista_filtered_data', (response) => {
// Process data before setting it
const processedData = processData(response.data);
setFilteredData(processedData);
// Update filter options based on data received
if (response.data && response.data.length > 0) {
const newFilterOptions = {
Country: [...new Set(response.data.map(item => item.Country).filter(Boolean))],
type: [...new Set(response.data.map(item => item.type).filter(Boolean))],
customer: [...new Set(response.data.map(item => item.customer).filter(Boolean))],
status: [...new Set(response.data.map(item => item.status).filter(Boolean))],
Tenor: [...new Set(response.data.map(item => item.Tenor).filter(Boolean))],
scope: [],
product: ['REV', 'REPO'],
};
setFilterOptions(newFilterOptions);
}
});
fetchFilteredData(filters);
const intervalId = setInterval(() => {
console.log("Requesting Stock Vista update...");
fetchFilteredData(filters);
}, 30 * 60 * 1000);
return () => {
unsubscribe();
clearInterval(intervalId);
};
}, [isConnected, fetchFilteredData, websocketService, processData, filters]);
useEffect(() => {
if (!isConnected) return;
const unsubscribe = websocketService.subscribe('stock_vista_stock', (response) => {
setStockdData(response.data)
});
code Copy code
fetchStockData(filters);
const intervalId = setInterval(() => {
console.log("Requesting Stock Vista update...");
fetchStockData(filters);
}, 30 * 60 * 1000);
return () => {
unsubscribe();
clearInterval(intervalId);
};
}, [isConnected, fetchStockData, websocketService, filters]);;
const handleFilterChange = useCallback((filterName, value) => {
const newFilters = {
...filters,
[filterName]: value === "all" ? null : value
};
code Copy code
setFilters(newFilters);
// Force immediate refresh of both data types
Promise.all([
fetchFilteredData(newFilters),
fetchStockData(newFilters)
]).then(() => {
setPage(0); // Reset to first page when filter changes
});
}, [filters, fetchFilteredData, fetchStockData]);
const handleChangePage = (event, newPage) => {
setPage(newPage);
};
const handleChangeRowsPerPage = (event) => {
setRowsPerPage(parseInt(event.target.value, 10));
setPage(0);
};
const handleRefresh = () => {
fetchFilteredData(filters);
};
const clearFilters = () => {
const clearedFilters = {
pays: null,
client_type: null,
customer: null,
status: null,
maturity: null,
scope: null,
product: null,
};
setFilters(clearedFilters);
fetchFilteredData(clearedFilters);
};
if (!isConnected) {
return (
Connexion interrompue : reconnexion au serveur en cours...
);
}
code Copy code
<Filters
filters={filters}
filterOptions={filterOptions}
filtersExpanded={filtersExpanded}
setFiltersExpanded={setFiltersExpanded}
handleFilterChange={handleFilterChange}
clearFilters={clearFilters}
/>
{/* Tabs Navigation */}
<Box sx={{ borderBottom: 1, borderColor: 'divider', mb: 3 }}>
<Tabs value={activeTab} onChange={handleTabChange}>
<Tab label="Graphiques" />
<Tab label="Données" />
<Tab label="Analytics" />
</Tabs>
</Box>
{/* Tab Panels */}
<div role="tabpanel" hidden={activeTab !== 0}>
{/* {activeTab === 0 && <GraphsTabContent />} */}
<div style={{ padding: '0rem' }}>
<h2>Long and Short Positions by Country</h2>
<StackedLongShortAreaChart data={stockData} />
</div>
</div>
<div role="tabpanel" hidden={activeTab !== 1}>
{activeTab === 1 && (
<DataTabContent
stockData={filteredData}
columns={columns}
page={page}
rowsPerPage={rowsPerPage}
handleChangePage={handleChangePage}
handleChangeRowsPerPage={handleChangeRowsPerPage}
/>
)}
</div>
<div role="tabpanel" hidden={activeTab !== 2}>
{activeTab === 2 && <AnalyticsTabContent />}
</div>
<div className="spacer"></div>
</Container>
export default StockVista;
The filtering doesn't update the graphs dynamically : can you see what could be wrong ?
It appears that the graphs in your StockVista component are not updating dynamically when filters are applied. This issue likely stems from the fetchStockData function not being called with the updated filters when they change. Let's address this by ensuring that fetchStockData is invoked whenever the filters state is updated.
Solution:
Update the handleFilterChange Function:
Modify the handleFilterChange function to call fetchStockData with the new filters immediately after updating the filters state. This ensures that the stock data is refreshed whenever a filter is changed.
javascript Copy code
const handleFilterChange = useCallback((filterName, value) => {
const newFilters = {
...filters,
[filterName]: value === "all" ? null : value
};
setFilters(newFilters);
// Fetch stock data with the new filters
fetchStockData(newFilters);
// Reset to the first page when filters change
setPage(0);
}, [filters, fetchStockData]);
Ensure fetchStockData is Defined Correctly:
Verify that the fetchStockData function is correctly defined and utilizes the latest filters. It should be a useCallback hook that depends on isConnected and websocketService to ensure it has access to the current state and props.
javascript Copy code
const fetchStockData = useCallback((appliedFilters) => {
if (isConnected) {
requestStockData(appliedFilters);
}
}, [isConnected, websocketService]);
Update the useEffect Hook for Stock Data:
Adjust the useEffect hook that subscribes to stock data updates to depend on the filters state. This ensures that the subscription is refreshed whenever the filters change.
javascript Copy code
useEffect(() => {
if (!isConnected) return;
const unsubscribe = websocketService.subscribe('stock_vista_stock', (response) => {
setStockData(response.data);
});
// Fetch stock data with the current filters
fetchStockData(filters);
const intervalId = setInterval(() => {
console.log("Requesting Stock Vista update...");
fetchStockData(filters);
}, 30 * 60 * 1000);
return () => {
unsubscribe();
clearInterval(intervalId);
};
}, [isConnected, fetchStockData, websocketService, filters]);
Explanation:
Immediate Data Fetching: By calling fetchStockData immediately after updating the filters state in handleFilterChange, you ensure that the stock data is refreshed without waiting for the next interval or user action.
Correct Dependencies: Ensuring that fetchStockData and the useEffect hook depend on the correct variables (isConnected, websocketService, and filters) guarantees that they have access to the latest state and props, leading to accurate and timely data fetching.
By implementing these changes, your graphs should update dynamically in response to filter changes, providing a more interactive and responsive user experience.
Copy first response