updating dataFetch components hooks
This commit is contained in:
parent
259fc07697
commit
1caa082f45
71
src/hooks/WordpressFetchData.js
Normal file
71
src/hooks/WordpressFetchData.js
Normal file
|
|
@ -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 };
|
||||
Loading…
Reference in New Issue
Block a user