16 Api documentation
Tim Svensson edited this page 2026-04-26 11:11:39 +00:00

Api documentation

Using shared apiCall function

When fetching data from an api the shared function useApi should be utilized. The function is located in following file.

frontend/src/features/utility/sharedFeatures.js

useApi returns following information.

  • data
    • The returned data is stored as a javascript object.
  • loading
    • Indicates if data is being loading.
      • Values.
        • True.
        • False.
      • While the value is true data is being loaded.
      • When data is done loading loading is set to false.
  • error
    • The default value of error is null.
    • If an error occurs the error message is stored here .
export function useApi(API_URL) {
  const [data, setData]       = useState(null);  // { timestamp, temperature }
  const [loading, setLoading] = useState(true);
  const [error, setError]     = useState(null);
 
  useEffect(() => {
    fetch(API_URL)
      .then(res => {
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return res.json();
      })
      .then(json => {
        setData(json);
        setError(null);
      })
      .catch(err => setError(err.message))
      .finally(() => setLoading(false));
  }, []);
 
  return { data, loading, error };
}

How to use

  • Import the function.
import { useApi } from '../utility/sharedFeatures.js';
  • Create a wrapper function for your service.
    • The function name should follow following naming convention
      • useServiceName
    • A const variable with the name API_URL should be created.
    • The variable should store the API url.
    • Return the function useApi with the argument API_URL.
    • Example
export function useTimeedit() {
  const dependency = null; // Replace null with the dependencies needed
  const API_URL = 'TEMP';
  return useApi(API_URL,dependency);
}