add lazy loading to AnalystEstimate component

This commit is contained in:
MuslemRahimi 2024-06-07 10:28:42 +02:00
parent f759268c22
commit 1a3d5a86e1
3 changed files with 139 additions and 75 deletions

View File

@ -1,5 +1,5 @@
<script lang='ts'> <script lang='ts'>
import {screenWidth} from '$lib/store'; import {stockTicker, screenWidth, userRegion, getCache, setCache} from '$lib/store';
import InfoModal from '$lib/components/InfoModal.svelte'; import InfoModal from '$lib/components/InfoModal.svelte';
import { LayerCake, Html } from 'layercake'; import { LayerCake, Html } from 'layercake';
@ -9,9 +9,23 @@ import AxisX from '$lib/components/Scatter//AxisX.html.svelte';
import AxisY from '$lib/components/Scatter//AxisY.html.svelte'; import AxisY from '$lib/components/Scatter//AxisY.html.svelte';
export let analystEstimateList;
export let data; export let data;
let analystEstimateList = [];
let isLoaded = false;
const usRegion = ['cle1','iad1','pdx1','sfo1'];
let apiURL;
userRegion.subscribe(value => {
if (usRegion.includes(value)) {
apiURL = import.meta.env.VITE_USEAST_API_URL;
} else {
apiURL = import.meta.env.VITE_EU_API_URL;
}
});
let deactivateContent = data?.user?.tier === 'Pro' ? false : true; let deactivateContent = data?.user?.tier === 'Pro' ? false : true;
let dataset = []; let dataset = [];
@ -51,10 +65,34 @@ const padding = 2.5;
let tableDataActual = []; let tableDataActual = [];
let tableDataForecast = [] let tableDataForecast = []
const getAnalystEstimate = async (ticker) => {
// Get cached data for the specific tickerID
const cachedData = getCache(ticker, 'getAnalystEstimate');
if (cachedData) {
analystEstimateList = cachedData;
} else {
const postData = {'ticker': ticker};
// make the POST request to the endpoint
const response = await fetch(apiURL + '/analyst-estimate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(postData)
});
analystEstimateList = await response?.json();
// Cache the data for this specific tickerID with a specific name 'getAnalystEstimate'
setCache(ticker, analystEstimateList, 'getAnalystEstimate');
}
};
//To-do: Optimize this piece of shit //To-do: Optimize this piece of shit
$: { function prepareData(analystEstimateList) {
if (displayData && analystEstimateList?.length !== 0)
{
dataset = []; dataset = [];
tableDataActual = []; tableDataActual = [];
tableDataForecast = []; tableDataForecast = [];
@ -123,6 +161,28 @@ $: {
dataset?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': item?.estimatedEbitdaAvg !== null ? (item?.estimatedEbitdaAvg / denominator)?.toFixed(2) : null, 'dataset': 'forecast' }); dataset?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': item?.estimatedEbitdaAvg !== null ? (item?.estimatedEbitdaAvg / denominator)?.toFixed(2) : null, 'dataset': 'forecast' });
}); });
} }
}
$: {
if ($stockTicker && displayData && typeof window !== 'undefined')
{
isLoaded = false;
const asyncFunctions = [
getAnalystEstimate($stockTicker)
];
Promise.all(asyncFunctions)
.then((results) => {
prepareData(analystEstimateList)
})
.catch((error) => {
console.error('An error occurred:', error);
});
isLoaded = true;
} }
@ -141,9 +201,6 @@ $: {
<main> <main>
<div class="w-fit sm:w-full sm:max-w-2xl m-auto mt-5 sm:mt-0"> <div class="w-fit sm:w-full sm:max-w-2xl m-auto mt-5 sm:mt-0">
{#if analystEstimateList?.length !== 0}
<div class="flex flex-row items-center"> <div class="flex flex-row items-center">
<label for="predictiveFundamentalsInfo" class="mr-1 cursor-pointer flex flex-row items-center text-white text-xl sm:text-3xl font-bold"> <label for="predictiveFundamentalsInfo" class="mr-1 cursor-pointer flex flex-row items-center text-white text-xl sm:text-3xl font-bold">
Predictive Fundamentals Predictive Fundamentals
@ -159,6 +216,9 @@ $: {
<div class="text-white text-sm sm:text-[1rem] mt-1 sm:mt-3 mb-1 w-full sm:w-5/6"> <div class="text-white text-sm sm:text-[1rem] mt-1 sm:mt-3 mb-1 w-full sm:w-5/6">
We analyze insights from various analysts to offer both historical and future fundamental data forecasts. We analyze insights from various analysts to offer both historical and future fundamental data forecasts.
</div> </div>
{#if isLoaded}
{#if analystEstimateList?.length !== 0}
<select class="mt-5 mb-5 sm:mb-0 sm:mt-3 ml-1 w-44 select select-bordered select-sm p-0 pl-5 overflow-y-auto bg-[#2A303C]" on:change={changeStatement}> <select class="mt-5 mb-5 sm:mb-0 sm:mt-3 ml-1 w-44 select select-bordered select-sm p-0 pl-5 overflow-y-auto bg-[#2A303C]" on:change={changeStatement}>
@ -283,6 +343,16 @@ $: {
</h2> </h2>
{/if} {/if}
{:else}
<div class="flex justify-center items-center h-80">
<div class="relative">
<label class="bg-[#202020] rounded-xl h-14 w-14 flex justify-center items-center absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2">
<span class="loading loading-spinner loading-md"></span>
</label>
</div>
</div>
{/if}
</div> </div>
</main> </main>
</div> </div>

View File

@ -142,7 +142,6 @@ export const load = async ({ params, locals, cookies}) => {
fetchData(apiURL,'/stockdeck',params.tickerID), fetchData(apiURL,'/stockdeck',params.tickerID),
fetchData(apiURL,'/stock-correlation',params.tickerID), fetchData(apiURL,'/stock-correlation',params.tickerID),
fetchData(apiURL,'/analyst-summary-rating',params.tickerID), fetchData(apiURL,'/analyst-summary-rating',params.tickerID),
fetchData(apiURL,'/analyst-estimate',params.tickerID),
fetchData(apiURL,'/stock-quote',params.tickerID), fetchData(apiURL,'/stock-quote',params.tickerID),
fetchData(apiURL,'/stock-rating',params.tickerID), fetchData(apiURL,'/stock-rating',params.tickerID),
fetchData(apiURL,'/options-bubble',params.tickerID), fetchData(apiURL,'/options-bubble',params.tickerID),
@ -167,7 +166,6 @@ export const load = async ({ params, locals, cookies}) => {
getStockDeck, getStockDeck,
getCorrelation, getCorrelation,
getAnalystRating, getAnalystRating,
getAnalystEstimate,
getStockQuote, getStockQuote,
getStockTARating, getStockTARating,
getOptionsData, getOptionsData,
@ -198,7 +196,6 @@ export const load = async ({ params, locals, cookies}) => {
getStockDeck, getStockDeck,
getCorrelation, getCorrelation,
getAnalystRating, getAnalystRating,
getAnalystEstimate,
getStockQuote, getStockQuote,
getStockTARating, getStockTARating,
getOptionsData, getOptionsData,

View File

@ -5,7 +5,6 @@
import { TrackingModeExitMode } from 'lightweight-charts'; import { TrackingModeExitMode } from 'lightweight-charts';
import {screenWidth, displayCompanyName, numberOfUnreadNotification, globalForm, userRegion, isCrosshairMoveActive, realtimePrice, priceIncrease, currentPortfolioPrice, currentPrice, clientSideCache, stockTicker, isOpen, isBeforeMarketOpen, isWeekend} from '$lib/store'; import {screenWidth, displayCompanyName, numberOfUnreadNotification, globalForm, userRegion, isCrosshairMoveActive, realtimePrice, priceIncrease, currentPortfolioPrice, currentPrice, clientSideCache, stockTicker, isOpen, isBeforeMarketOpen, isWeekend} from '$lib/store';
import { onDestroy, onMount } from 'svelte'; import { onDestroy, onMount } from 'svelte';
import AnalystEstimate from '$lib/components/AnalystEstimate.svelte';
import StockKeyInformation from '$lib/components/StockKeyInformation.svelte'; import StockKeyInformation from '$lib/components/StockKeyInformation.svelte';
import BullBearSay from '$lib/components/BullBearSay.svelte'; import BullBearSay from '$lib/components/BullBearSay.svelte';
import CommunitySentiment from '$lib/components/CommunitySentiment.svelte'; import CommunitySentiment from '$lib/components/CommunitySentiment.svelte';
@ -31,7 +30,6 @@
let pricePrediction = data?.getPricePrediction ?? []; let pricePrediction = data?.getPricePrediction ?? [];
let stockDeck = data?.getStockDeck ?? []; let stockDeck = data?.getStockDeck ?? [];
let analystEstimateList = data?.getAnalystEstimate ?? []
let fairPrice = data?.getFairPrice ?? []; let fairPrice = data?.getFairPrice ?? [];
let correlationList = data?.getCorrelation?.correlation ?? []; let correlationList = data?.getCorrelation?.correlation ?? [];
let modelStats = data?.getTradingSignals ?? {}; let modelStats = data?.getTradingSignals ?? {};
@ -73,7 +71,6 @@
//let StockKeyInformation; //let StockKeyInformation;
//let AnalystEstimate;
@ -641,7 +638,6 @@ function changeChartType() {
modelStats = data?.getTradingSignals; modelStats = data?.getTradingSignals;
stockDeck = data?.getStockDeck; stockDeck = data?.getStockDeck;
correlationList = data?.getCorrelation?.correlation; correlationList = data?.getCorrelation?.correlation;
analystEstimateList = data?.getAnalystEstimate;
previousClose = data?.getStockQuote?.previousClose; previousClose = data?.getStockQuote?.previousClose;
marketMoods = data?.getBullBearSay; marketMoods = data?.getBullBearSay;
taRating = data?.getStockTARating; taRating = data?.getStockTARating;
@ -1242,13 +1238,14 @@ function changeChartType() {
{/if} {/if}
<div class="w-full m-auto sm:pl-6 sm:pb-6 sm:pt-6 {analystEstimateList?.length !== 0 ? '' : 'hidden'}">
{#if AnalystEstimate}
<AnalystEstimate data={data} analystEstimateList={analystEstimateList}/>
{/if}
<Lazy>
<div class="w-full m-auto sm:pl-6 sm:pb-6 sm:pt-6">
{#await import('$lib/components/AnalystEstimate.svelte') then {default: Comp}}
<svelte:component this={Comp} data={data}/>
{/await}
</div> </div>
</Lazy>
<Lazy> <Lazy>