From 4cdb527f7dea9620af427bada8f3cd961a99b482 Mon Sep 17 00:00:00 2001 From: VividTruthKeeper Date: Fri, 10 Feb 2023 01:22:36 +0500 Subject: [PATCH] api fetch prevention w/ redux --- src/components/global/NewsScroll.tsx | 96 ++++++++++++++++------------ 1 file changed, 55 insertions(+), 41 deletions(-) diff --git a/src/components/global/NewsScroll.tsx b/src/components/global/NewsScroll.tsx index 561b6fc..7a612da 100644 --- a/src/components/global/NewsScroll.tsx +++ b/src/components/global/NewsScroll.tsx @@ -1,61 +1,75 @@ +// Modules +import { useEffect, useState } from "react"; +import { v4 as uuidv4 } from "uuid"; +import { useSelector, useDispatch } from "react-redux"; + // Components import News from "../news/News"; import SectionTitle from "./SectionTitle"; -// Images -import placeholder from "../../assets/images/placeholder.jpg"; +import Loader from "./Loader"; + +// Api +import { url } from "../../url"; +import { Api } from "../../api/Api"; +import { newsScrollParams } from "../../api/params"; + +// Types +import { IPostsData } from "../../types/data.types"; +import { ILanguage, RootState } from "../../types/store.types"; + +// Actions +import { setNewsScroll } from "../../actions/setData"; -// Interface interface Props { - state: boolean; + title: boolean; } -const NewsScroll = ({ state }: Props) => { +const NewsScroll = ({ title }: Props) => { + const api = new Api(url + "/posts", newsScrollParams); + const language = api.language; + const [lastLanguage, setLastLanguage] = useState(language); + + // redux + const data = useSelector( + (state) => state.dataReducer.data + ); + const dispatch = useDispatch(); + + useEffect(() => { + if (!(data[0].id > -1 && lastLanguage === language)) { + api.get(data, (data: IPostsData[]) => dispatch(setNewsScroll(data))); + setLastLanguage(language); + } + }, [language, lastLanguage]); + return (
- {state === true ? ( + {title === true ? ( ) : null}
- - - - - + {data ? ( + data.map((dataEl) => { + return ( + + ); + }) + ) : ( + + )}