import useSWR from "swr";
import axios from "@agir/lib/utils/axios";

const WP_API_URL = "https://infos.actionpopulaire.fr/wp-json/wp/v2/";
const WP_PAGE_URL = `${WP_API_URL}pages?per_page=100&&_embed=wp:term,wp:featuredmedia`;
const CATEGORY_LIST = [15, 16, 17];

const fetcher = async (url) => {
  const res = await axios.get(url);
  return res.data;
};

/** return [categories, pages] */
export const getWPPagesAndCategories = () => {
  const { data } = useSWR(
    `${WP_PAGE_URL}&categories=${CATEGORY_LIST.toString()}`,
    fetcher,
    {
      revalidateOnFocus: false,
      refreshInterval: 0,
      refreshWhenHidden: false,
    }
  );

  let categories = [];
  const pages = data?.reduce((pagesSorted, page) => {
    const page_categories = page._embedded["wp:term"];
    const filtered_categories = page_categories.reduce((res, cat) => {
      const cat_filtered = cat.filter(
        (c) => c.taxonomy === "category" && CATEGORY_LIST.includes(c.id),
        []
      );
      return [...res, ...cat_filtered];
    }, []);

    // Add to category list
    const category = filtered_categories[0];
    categories[category.id] = { id: category.id, name: category.name };

    const p = {
      id: page.id,
      title: page.title.rendered,
      img: page._embedded["wp:featuredmedia"][0].source_url,
      link: page.link,
      category_id: category.id,
      category_name: category.name,
    };

    if (!pagesSorted[category.id]) pagesSorted[category.id] = [p];
    else pagesSorted[category.id].push(p);

    return pagesSorted;
  }, []);

  return [categories, pages];
};

@@ -22,51 +22,8 @@
 wr%22;
-%0Aimport axios from %22@agir/lib/utils/axios%22;
 %0A%0Aco
@@ -219,99 +219,8 @@
 %5D;%0A%0A
-const fetcher = async (url) =%3E %7B%0A  const res = await axios.get(url);%0A  return res.data;%0A%7D;%0A
 %0A/**
@@ -324,16 +324,16 @@
 useSWR(%0A
+
     %60$%7BW
@@ -389,21 +389,8 @@
 %7D%60,%0A
-    fetcher,%0A
     

remove useless fetcher declaration