willayy / DAT257-Agile

Agile project in DAT257
1 stars 0 forks source link

Fetch data from police api #10

Closed willayy closed 6 months ago

willayy commented 6 months ago

During US-004 we implemented an async data fetching function that can be called in other async react component methods. The testing example we used looked like this.

  import Image from "next/image";
  import styles from "./page.module.css";
  import { getCrimeData } from "../scripts/dataFetching";

  export default async function Home() {

    const data = await getCrimeData();

    return (  
      <main>
        <h1> test </h1>
        <p>{data[0].id}</p>
        <p>{data[0].datetime}</p>
        <p>{data[0].name}</p>
        <p>{data[0].summary}</p>
        <p>{data[0].url}</p>
        <p>{data[0].type}</p>
        <p>{data[0].location.name}</p>
        <p>{data[0].location.gps}</p>
      </main>
    );
  }

This is pretty much just the basic homepage page.tsx file but with some added paragraphs to display the fetched data. however its very import to notice that instead of the usual function signature of

export default function Home()

We used

export default async function Home()

Because if we didn't the async data fetching wouldn't work.

The function also comes with a built in stop switch that returns a cached data package if to many requests are sent, to configure the URL or the allowed calls per minute please use the constants in dataFetching.ts

// Configs for the data fetch
const url: URL = new URL("https://polisen.se/api/events");
const fetchingTimeframe = 60; // This is the timeframe in seconds that the data is cached for

We also decided it would be best to put the script in agile-app/src/scripts for the sake of encapsulation and modularity.

The function uses the next fetch() function to fetch data and to ensure we don't call the api too much. This is described in detail on Next.js

jmarkusson commented 6 months ago

Looks good!