- npx create-next-app -e with-tailwindcss frontend
- cd frontend
- npm run dev
- update pages/index.tsx
- create .env
NEXT_PUBLIC_API_URL = 'http://127.0.0.1:8000'
- update package.json
"name": "frontend",
"proxy": "http://127.0.0.1",
"version": "0.1.0",
- npm run dev
- npm install axios
- npm install --save-dev @types/axios
- update pages/index.tsx to use axios to fetch data from backend
let LiveDataHandler: any;
const Home: NextPage = () => {
// useState and useEffect
// get request with timeout every 5 seconds using timerIsActive and timerDuration
const [timerIsActive, setTimerIsActive] = useState(false);
const [timerDuration, setTimerDuration] = useState(500);
const [data, setData] = useState([]);
async function FetchLiveHandler() {
try {
const response = await axios.get("http://localhost:8000/api/dashboard");
setData(response.data);
} catch (error) {
console.log(error);
}
}
useEffect(() => {
if (!timerIsActive) {
setTimerIsActive(true);
setTimerDuration(2000);
LiveDataHandler = setTimeout(() => {
FetchLiveHandler();
setTimerIsActive(false);
}, timerDuration);
}
}, [timerIsActive, timerDuration, FetchLiveHandler]);
//console.log(data);
return (
<div className="flex min-h-screen flex-col items-center justify-center py-2">
<Head>
<title>Create Next App</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main className="flex w-full flex-1 flex-col items-center justify-center px-20 text-center">
{/** map through the data and get data.match_status property and use it in h1 tag **/}
{data.map((item: any, index: any) => (
<h1 key={index} className="text-6xl font-bold">
Minute: {item.match_status}, goal_pred: {item.goal_pred}
</h1>
))}
</main>
- fix CORS issue in backend
MIDDLEWARE = ["corsheaders.middleware.CorsMiddleware",]
INSTALLED_APPS = ["corsheaders",]
CORS_ALLOW_ALL_ORIGINS = True
- Render data in frontend
{
/** map through the data and get data.match_status property and use it in h1 tag **/
}
<main className="flex w-full flex-1 flex-col items-center justify-center px-20 text-center">
<h1 className="text-2xl font-bold">Welcome to My Dashboard </h1>
{data.map((item: any, index: any) => (
<h1 key={index} className="text-2xl font-bold">
Minute: {item.match_status}, goal_pred: {item.goal_pred}
</h1>
))}
</main>;
- set interval for fetching every 2 seconds using setInterval function:
useEffect(() => {
const interval = setInterval(() => {
FetchLiveHandler();
}, 2000);
return () => clearInterval(interval);
}, []);
- .env file
NEXT_PUBLIC_API_URL = 'http://localhost:8000'
- npm run build