Skip to content
The Chat Archive
gpt-4o-search-preview-high· OpenAI LMArena Search Arena 24K

// src/pages/StockVista/StockVista.js import React, { useEffect, useState, useCallback }…

  1. User

    // 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); }

      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 [];

    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
    }));
    

    }, [formatDate]);

    useEffect(() => { if (!isConnected) return;

    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) });

    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 };

    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... ); }

    return ( Stock Vista

      <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 ?

  2. Assistant

    It appears that the graphs in your StockVista component are not updating dynamically when filters are applied. This issue likely stems from how the fetchStockData function is utilized within your component. Let's examine the potential causes and solutions:

    1. Dependency Array in useEffect:

    In your current implementation, the useEffect hook responsible for fetching stock data is set up as follows:

    useEffect(() =&gt; {
      if (!isConnected) return;
      const unsubscribe = websocketService.subscribe('stock_vista_stock', (response) =&gt; {
        setStockdData(response.data);
      });
    
      fetchStockData(filters);
    
      const intervalId = setInterval(() =&gt; {
        console.log("Requesting Stock Vista update...");
        fetchStockData(filters);
      }, 30 * 60 * 1000);
    
      return () =&gt; {
        unsubscribe();
        clearInterval(intervalId);
      };
    }, [isConnected, fetchStockData, websocketService, filters]);
    

    Here, the useEffect hook depends on isConnected, fetchStockData, websocketService, and filters. This setup ensures that the effect runs when any of these dependencies change. However, if fetchStockData is memoized using useCallback without including filters in its dependency array, it may not reflect the latest filter values.

    2. Memoization of fetchStockData:

    Your fetchStockData function is defined as:

    const fetchStockData = useCallback((appliedFilters) =&gt; {
      if (isConnected) {
        requestStockData(appliedFilters);
      }
    }, [isConnected]);
    

    In this setup, fetchStockData is memoized with isConnected as its sole dependency. This means that fetchStockData will not change unless isConnected changes, potentially leading to stale references to filters.

    Solution:

    To ensure that fetchStockData always has access to the latest filter values, you can include filters in its dependency array and adjust its implementation accordingly:

    const fetchStockData = useCallback(() =&gt; {
      if (isConnected) {
        requestStockData(filters);
      }
    }, [isConnected, filters]);
    

    With this change, fetchStockData will be recreated whenever isConnected or filters change, ensuring it always uses the current filter values.

    3. Updating the Graphs:

    Ensure that the component responsible for rendering the graphs (StackedLongShortAreaChart) receives the updated stockData as a prop. This component should be designed to re-render whenever its data prop changes. For example:

    function StackedLongShortAreaChart({ data }) {
      useEffect(() =&gt; {
        // Logic to update the chart with new data
      }, [data]);
    
      // Render the chart
    }
    

    By ensuring that fetchStockData is correctly memoized and always uses the latest filters, and that your graph component re-renders when its data prop changes, the graphs should update dynamically in response to filter changes.

    Additional Considerations:

    • State Management: Ensure that stockData is correctly updated in your state management logic. Any issues in setting or updating this state can affect the rendering of your graphs.

    • WebSocket Handling: Verify that the WebSocket subscription is correctly set up to receive and process updates. Any issues in the subscription logic can lead to stale or missing data.

    By addressing these areas, you should be able to achieve dynamic updates to your graphs in response to filter changes.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.