From 1caa082f454a672f086014fc2619f98ff2cf2497 Mon Sep 17 00:00:00 2001 From: Antoine M Date: Tue, 30 Jan 2024 17:14:39 +0100 Subject: [PATCH] updating dataFetch components hooks --- src/hooks/WordpressFetchData.js | 71 +++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 src/hooks/WordpressFetchData.js diff --git a/src/hooks/WordpressFetchData.js b/src/hooks/WordpressFetchData.js new file mode 100644 index 0000000..e6f13ff --- /dev/null +++ b/src/hooks/WordpressFetchData.js @@ -0,0 +1,71 @@ +import { useEffect, useState } from "react"; +import { useLanguage } from "./useLanguage"; + +const BASE_URL = "http://lhoist-stay-safe.local/wp-json/wp/v2"; +const BASE_CUSTOM_URL = "http://lhoist-stay-safe.local/wp-json/lhoist-datas"; +const apiToken = process.env.REACT_APP_API_TOKEN; + +function useWordpressCustomData(url) { + const [data, setData] = useState(); + const { language } = useLanguage(); + const fullUrl = `${BASE_CUSTOM_URL}${url}?current-page-language=${language}`; + + useEffect(() => { + const dataFetch = async () => { + const data = await (await fetch(fullUrl)).json(); + + setData(data); + }; + + dataFetch(); + }, [language, fullUrl]); + + return data; +} +function useWordpressData(url) { + const [data, setData] = useState(); + + useEffect(() => { + const dataFetch = async () => { + const data = await (await fetch(BASE_URL + url)).json(); + + setData(data); + }; + + dataFetch(); + }, [url]); + + return data; +} +async function postWordpressStatisticsData(url) { + const requestData = { + user_name: "Antoine", + user_locale: "fr", + user_country: "France", + level_post_id: 154, + level_is_completed: 0, + level_completion_time: 20000, + level_score: 12, + }; + + try { + const response = await fetch(BASE_CUSTOM_URL + url, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${apiToken}`, + }, + body: JSON.stringify(requestData), + }); + + if (!response.ok) { + throw new Error(`Erreur lors de la récupération des données depuis ${BASE_CUSTOM_URL + url}`); + } + + const responseData = await response.json(); + return responseData; + } catch (error) { + console.error(error); + } +} +export { useWordpressData, useWordpressCustomData, postWordpressStatisticsData };