skolplattformen-backup/libs/hooks
Andreas Eriksson 20ee509c28 style: 💄 Add eslint rules to api-skolplattformen and autofix
Add react-native-community eslint rules to project and run autofix on
all files.
2022-04-24 20:27:10 +02:00
..
src style: 💄 Add eslint rules to api-skolplattformen and autofix 2022-04-24 20:27:10 +02:00
.babelrc Fix tests for `hooks` 2021-10-15 22:36:48 +02:00
.eslintrc.json fix: lint and prettier fixes 2021-10-06 22:47:50 +02:00
.gitignore Moved api-hooks project to subdirectory before merge to monorepo 2021-10-03 11:50:00 +02:00
.releaserc Moved api-hooks project to subdirectory before merge to monorepo 2021-10-03 11:50:00 +02:00
LICENSE Moved api-hooks project to subdirectory before merge to monorepo 2021-10-03 11:50:00 +02:00
README.md feat: 🎸 Fix image load and typescript errors (#570) 2021-12-02 15:34:15 +01:00
jest.config.js Fix tests for `hooks` 2021-10-15 22:36:48 +02:00
package.json Fix tests for `hooks` 2021-10-15 22:36:48 +02:00
project.json feat: 🎸 bump to RN 0.66 + upgrade dependencies (#521) 2021-12-16 08:22:20 +01:00
tsconfig.json feat: add nx build system 2021-10-05 17:27:47 +02:00
tsconfig.lib.json feat: add nx build system 2021-10-05 17:27:47 +02:00
tsconfig.spec.json Fix tests for `hooks` 2021-10-15 22:36:48 +02:00

README.md

hooks

  1. Installing
  2. Login / logout
  3. Get data
  4. Fake mode

Installing

npm i -S hooks @skolplattformen/embedded-api

yarn add hooks @skolplattformen/embedded-api

ApiProvider

In order to use api hooks, you must wrap your app in an ApiProvider

import React from 'react'
import { ApiProvider } from '@skolplattformen/hooks'
import init from '@skolplattformen/api-skolplattformet'
import { CookieManager } from '@react-native-cookies/cookies'
import AsyncStorage from '@react-native-async-storage/async-storage'
import { RootComponent } from './components/root'
import crashlytics from '@react-native-firebase/crashlytics'

const api = init(fetch, () => CookieManager.clearAll())
const reporter = {
  log: (message) => crashlytics().log(message),
  error: (error, label) => crashlytics().recordError(error, label),
}

export default () => (
  <ApiProvider api={api} reporter={reporter} storage={AsyncStorage}>
    <RootComponent />
  </ApiProvider>
)

Login / logout

import { useApi } from '@skolplattformen/hooks'

export default function LoginController () {
  const { api, isLoggedIn } = useApi()

  api.on('login', () => { /* do login stuff */ })
  api.on('logout', () => { /* do logout stuff */ })

  const [personalNumber, setPersonalNumber] = useState()
  const [bankIdStatus, setBankIdStatus] = useState('')

  const doLogin = async () => {
    const status = await api.login(personalNumber)

    openBankID(status.token)

    status.on('PENDING', () => { setBankIdStatus('BankID app not yet opened') })
    status.on('USER_SIGN', () => { setBankIdStatus('BankID app is open') })
    status.on('OK', () => { setBankIdStatus('BankID signed. NOTE! User is NOT yet logged in!') })
    status.on('ERROR', (err) => { setBankIdStatus('BankID failed') })
  })

  return (
    <View>
      <Input value={personalNumber} onChange={(value) = setPersonalNumber(value)} />
      <Button onClick={() => doLogin()}>
      <Text>{bankIdStatus}</Text>
      <Text>Logged in: {isLoggedIn}</Text>
    </View>
  )
}

Get data

  1. General
  2. useCalendar
  3. useChildList
  4. useClassmates
  5. useMenu
  6. useNews
  7. useNotifications
  8. useSchedule
  9. useUser

General

The data hooks return a State<T> object exposing the following properties:

Property Description
status pending loading loaded
data The requested data
error Error from the API call if any
reload Function that triggers a reload

The hook will return a useable default for data at first (usually empty []). It then checks the cache (AsyncStorage) for any value and, if exists, updates data. Simultaneously the API is called. This only automatically happens once during the lifetime of the app. If several instances of the same hook are used, the data will be shared and only one API call made. When reload is called, a new API call will be made and all hook instances will have their status, data and error updated.

useCalendar

import { useCalendar } from '@skolplattformen/hooks'

export default function CalendarComponent ({ selectedChild }) => {
  const { status, data, error, reload } = useCalendar(selectedChild)

  return (
    <View>
      { status === 'loading' && <Spinner />}
      { error && <Text>{ error.message }</Text>}
      { data.map((item) => (
        <CalendarItem item={item} />
      ))}
      { status !== 'loading' && status !== 'pending' && <Button onClick={() => reload()}> }
    </View>
  )
}

useChildList

import { useChildList } from '@skolplattformen/hooks'

export default function ChildListComponent () => {
  const { status, data, error, reload } = useChildList()

  return (
    <View>
      { status === 'loading' && <Spinner />}
      { error && <Text>{ error.message }</Text>}
      { data.map((child) => (
        <Text>{child.firstName} {child.lastName}</Text>
      ))}
      { status !== 'loading' && status !== 'pending' && <Button onClick={() => reload()}> }
    </View>
  )
}

useClassmates

import { useClassmates } from '@skolplattformen/hooks'

export default function ClassmatesComponent ({ selectedChild }) => {
  const { status, data, error, reload } = useClassmates(selectedChild)

  return (
    <View>
      { status === 'loading' && <Spinner />}
      { error && <Text>{ error.message }</Text>}
      { data.map((classmate) => (
        <Classmate item={classmate} />
      ))}
      { status !== 'loading' && status !== 'pending' && <Button onClick={() => reload()}> }
    </View>
  )
}

useMenu

import { useMenu } from '@skolplattformen/hooks'

export default function MenuComponent ({ selectedChild }) => {
  const { status, data, error, reload } = useMenu(selectedChild)

  return (
    <View>
      { status === 'loading' && <Spinner />}
      { error && <Text>{ error.message }</Text>}
      { data.map((item) => (
        <MenuItem item={item} />
      ))}
      { status !== 'loading' && status !== 'pending' && <Button onClick={() => reload()}> }
    </View>
  )
}

useNews

import { useNews } from '@skolplattformen/hooks'

export default function NewsComponent ({ selectedChild }) => {
  const { status, data, error, reload } = useNews(selectedChild)

  return (
    <View>
      { status === 'loading' && <Spinner />}
      { error && <Text>{ error.message }</Text>}
      { data.map((item) => (
        <NewsItem item={item} />
      ))}
      { status !== 'loading' && status !== 'pending' && <Button onClick={() => reload()}> }
    </View>
  )
}

To display image from NewsItem:

import { useApi } from '@skolplattformen/hooks'

export default function NewsItem ({ item }) => {
  const { api } = useApi()
  const cookie = api.getSessionCookie()

  return (
    <View>
      { cookie &&
        <Image source={{ uri: item.fullImageUrl, headers: { cookie } }} /> }
    </View>
  )
}

useNotifications

import { useNotifications } from '@skolplattformen/hooks'

export default function NotificationsComponent ({ selectedChild }) => {
  const { status, data, error, reload } = useNotifications(selectedChild)

  return (
    <View>
      { status === 'loading' && <Spinner />}
      { error && <Text>{ error.message }</Text>}
      { data.map((item) => (
        <Notification item={item} />
      ))}
      { status !== 'loading' && status !== 'pending' && <Button onClick={() => reload()}> }
    </View>
  )
}

To show content of NotificationItem url:

import { useApi } from '@skolplattformen/hooks'
import { WebView } from 'react-native-webview'

export default function Notification ({ item }) => {
  const { cookie } = useApi()

  return (
    <View>
      <WebView source={{ uri: item.url, headers: { cookie }}} />
    </View>
  )
}

useSchedule

import { DateTime } from 'luxon'
import { useSchedule } from '@skolplattformen/hooks'

export default function ScheduleComponent ({ selectedChild }) => {
  const from = DateTime.local()
  const to = DateTime.local.plus({ week: 1 })
  const { status, data, error, reload } = useSchedule(selectedChild, from, to)

  return (
    <View>
      { status === 'loading' && <Spinner />}
      { error && <Text>{ error.message }</Text>}
      { data.map((item) => (
        <ScheduleItem item={item} />
      ))}
      { status !== 'loading' && status !== 'pending' && <Button onClick={() => reload()}> }
    </View>
  )
}

useUser

import { useUser } from '@skolplattformen/hooks'

export default function UserComponent () => {
  const { status, data, error, reload } = useUser()

  return (
    <View>
      { status === 'loading' && <Spinner />}
      { error && <Text>{ error.message }</Text>}
      { data &&
        <>
          <Text>{data.firstName} {data.lastName}</Text>
          <Text>{data.email}</Text>
        </>
      }
      { status !== 'loading' && status !== 'pending' && <Button onClick={() => reload()}> }
    </View>
  )
}

Fake mode

To make testing easier, fake mode can be enabled at login. Just use any of the magic personal numbers: 12121212121212, 201212121212 or 1212121212. The returned login status will have token set to 'fake'.

import { useApi } from '@skolplattformen/hooks'


import { useApi } from '@skolplattformen/hooks'

export default function LoginController () {
  const { api, isLoggedIn } = useApi()

  const [personalNumber, setPersonalNumber] = useState()
  const [bankIdStatus, setBankIdStatus] = useState('')

  api.on('login', () => { /* do login stuff */ })
  api.on('logout', () => { /* do logout stuff */ })

  const doLogin = async () => {
    const status = await api.login(personalNumber)

    if (status.token !== 'fake') {
      openBankID(status.token)
    } else {
      // Login will succeed
      // All data will be faked
      // No server calls will be made
    }
  })

  return (
    <View>
      <Input value={personalNumber} onChange={(value) = setPersonalNumber(value)} />
      <Button onClick={() => doLogin()}>
      <Text>{bankIdStatus}</Text>
      <Text>Logged in: {isLoggedIn}</Text>
    </View>
  )
}