diff --git a/src/api/Api.ts b/src/api/Api.ts new file mode 100644 index 0000000..6fe47e6 --- /dev/null +++ b/src/api/Api.ts @@ -0,0 +1,42 @@ +// Modules +import axios from "axios"; +import { Dispatch, SetStateAction } from "react"; +import { useSelector } from "react-redux"; + +// Types +import { IurlParamAdder } from "../types/api.types"; +import { RootState } from "../types/store.types"; + +// Helpers +import { urlParamAdder } from "../helpers/urlParamAdder"; + +export class Api { + url: string = ""; + params?: IurlParamAdder[]; + language = useSelector( + (state) => state.language.title + ); + + constructor(url: string, params?: IurlParamAdder[]) { + this.url = url; + this.params = params; + } + + get(state: any, setState: Dispatch>) { + const locale = { name: "locale", value: this.language }; + if ( + this.url.match( + "^(http(s)://.)[-a-zA-Z0-9@:%._+~#=]{2,256}.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)$" + ) + ) + throw new Error("Bad URL"); + axios + .get(urlParamAdder(locale, this.url, this.params)) + .then((res) => { + setState(res.data); + }) + .catch((err) => { + throw new Error(err); + }); + } +} diff --git a/src/components/header/SubNav.tsx b/src/components/header/SubNav.tsx index 4563db9..a9c019b 100644 --- a/src/components/header/SubNav.tsx +++ b/src/components/header/SubNav.tsx @@ -3,9 +3,10 @@ import { Link } from "react-router-dom"; import { v4 as uuidv4 } from "uuid"; import { motion } from "framer-motion"; import { useDispatch, useSelector } from "react-redux"; +import { useEffect, useState } from "react"; // Types -import { ActiveLinkType, RootState } from "../../types/store.types"; +import { RootState } from "../../types/store.types"; // Actions import { setActiveLink } from "../../actions/setActiveLink.action"; @@ -13,6 +14,10 @@ import { setActiveLink } from "../../actions/setActiveLink.action"; // Animations import { linkMotion } from "../../animations/subNav.animations"; +// Api +import { Api } from "../../api/Api"; +import { url } from "../../url"; + interface subNavDataType { data: string; link: string; @@ -64,12 +69,26 @@ const SubNav = () => { const activeLink = useSelector( (state) => state.activeLink.active ); + const language = useSelector( + (state) => state.language.title + ); + const dispatch = useDispatch(); const onClickLink = (active: number) => { dispatch(setActiveLink(active)); }; + const [data, setData] = useState(); + + // Api + const api = new Api(url + "/categories"); + + useEffect(() => { + api.get(data, setData); + }, [language]); + console.log(data); + return (