這是我的code:
import React, { Suspense } from "react";
import BusTable from "./BusTable"; // Assuming you have a BusTable component
import Loading from "./Loading"; // Assuming you have a Loading component
export default function App() {
return (
<Suspense fallback={<Loading />}>
<BusTable />
</Suspense>
);
}
import React from "react";
import { useKMB } from "./useKMB";
export default function BusTable() {
const { data, error } = useKMB();
if (error) {
// Handle the error (e.g., display an error message)
return <div>Error: {error.message}</div>;
}
return (
<div>
{data.map((d, i) => (
<div key={i}>
{d.name_tc} - {d.name_en}
</div>
))}
</div>
);
}
// useKMB.js
import { useEffect, useReducer } from "react";
import axios from "axios";
const initialState = {
data: [],
error: null,
};
const reducer = (state, action) => {
switch (action.type) {
case "init":
return { ...state, data: action.data };
case "setError":
return { ...state, error: action.error };
default:
return state;
}
};
export function useKMB() {
const [state, dispatch] = useReducer(reducer, initialState);
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get(
"https://data.etabus.gov.hk/v1/transport/kmb/stop"
);
dispatch({ type: "init", data: response.data.data });
} catch (error) {
dispatch({ type: "setError", error });
}
};
fetchData();
}, []);
return state;
}
現在可以顯示到資料,但是loading image 沒有出來,所以我都不肯定這是否work,求高人指點.