简体   繁体   中英

Fetching Data using custom hook on React

I am using vercel to deploy but I cannot figure out how to set up environmental variables, so I want to try method using fetch("/data.json"). I also have custom hook for fetching data. But this does not work and I don't even see data on my local. data.json file is directly inside /public folder. Can someone help me?

useFetch.js

import { useState, useEffect } from "react";

export const useFetch = (url, method = "GET") => {
  const [data, setData] = useState(null);
  const [isPending, setIsPending] = useState(false);
  const [error, setError] = useState(null);
  const [options, setOptions] = useState(null);

  const postData = (postData) => {
    setOptions({
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(postData),
    });
  };

  useEffect(() => {
    const controller = new AbortController();
    const fetchData = async (fetchOptions) => {
      setIsPending(true);

      try {
        const res = await fetch(url, {
          ...fetchOptions,
          signal: controller.signal,
        });
        if (!res.ok) {
          throw new Error(res.statusText);
        }
        const json = await res.json();

        setIsPending(false);
        setData(json);
        setError(null);
      } catch (err) {
        if (err.name === "AbortError") {
          console.log("the fetch was aborted");
        } else {
          setIsPending(false);
          setError("Could not fetch the data");
        }
      }
    };
    if (method === "GET") {
      fetchData();
    }
    if (method === "POST" && options) {
      fetchData(options);
    }
    return () => {
      controller.abort();
    };
  }, [url, options, method]);
  return { data, isPending, error, postData };
};

TaskList.js

import { useFetch } from "../hooks/useFetch";

import { useFrequency } from "../hooks/useFrequency";

//images
import Dot from "../assets/icon-ellipsis.svg";

// styles
import "./TaskList.scss";

export default function TaskList() {
  // const [url, setUrl] = useState("http://localhost:3000/stats");
  const { data: stats, isPending, error } = useFetch("/data.json");

  const { frequency } = useFrequency();
  const urlDot = "#";
  return (
    <div className="main__inner">
      {isPending && <div>Loading stats...</div>}
      {error && <div>{error}</div>}
      <ul className="main__task-list">
        {stats &&
          stats.map((stat) => (
            <li
              className={
                stat.title === "Self Care"
                  ? "main__task-item selfcare"
                  : `main__task-item ${stat.title.toLowerCase()}`
              }
              key={stat.id}
            >
              <div className="main__task-item-container">
                <h3 className="main__task-title">{stat.title}</h3>
                <a href={urlDot} className="main__task-dot">
                  <img src={Dot} alt="more details" />
                </a>
                <span className="main__task-current">
                  {/* {frequency === "daily"
                    ? stat.timeframes.daily.current
                    : frequency === "weekly"
                    ? stat.timeframes.weekly.current
                    : stat.timeframes.monthly.current}
                  hrs */}
                  {stat.timeframes[frequency].current}hrs
                </span>
                <span className="main__task-previous">
                  {frequency === "daily"
                    ? "Yesterday"
                    : frequency === "weekly"
                    ? "Last Week"
                    : "Last Month"}{" "}
                  -{" "}
                  {
                    /* {frequency === "daily"
                    ? stat.timeframes.daily.previous
                    : frequency === "weekly"
                    ? stat.timeframes.weekly.previous
                    : stat.timeframes.monthly.previous} */
                    stat.timeframes[frequency].previous
                  }
                  hrs
                </span>
              </div>
            </li>
          ))}
      </ul>
    </div>
  );
}

You can configure the Environment variable in Vercel after you have imported your site from GitHub or another repository.

You can set it on the Configure Project window by clicking the Environment Variable Tab . See the image below在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM