Tutorial

Handling Data

This is one part of a multi part tutorial on getting started with a new application.

getting data from your API Interface

Loading data is asynchronous, so using data from your API is more annoying than you'd think. Your React needs to have something valid to render at every stage of your data load -- so you have to keep track of states like haven't-started-yet (even if you start loading data the moment your app starts, you'll probably need to handle this state for the very first render of your app), data-is-still-arriving, and the-API-server-threw-an-error.

To help manage this, Spark provides a convenient hook: useApiFetch. The docs for useApiFetch are great, go read them, but the simplest usage looks like this:

require { useApiFetch, FetchStatus } from '@jcu/spark'

// do the fetching
const [errors, data, status] = useApiFetch(
    'api-name', '1',
    (api) => api.getSomeData()
)

// show the data, if we have it
if (status === FetchStatus.DATA) {
    return <InfoRenderer info={data} />
} else {
    return "please wait"
}

To use this example, you need to:

  • supply your own API Interface's name and version in place of the 'api-name', '1'
  • change the api.getSomeData() to call some method in your own API Interface
  • do something real with data (replacing InfoRenderer in the example code)

<< Previous Next >>
API Interfaces