npm package: @mycujoo/mcls-data-providers
Description: MCLS react context providers and utils for data fetching.
Latest version: 1.0.2-rc.3

# MCLS data providers

MCLS react context providers and utils for data fetching.

## Event state

### `EventContext`

This is a react context holding event information.

* `isLoading`: boolean / default true - This indicates if the event state finished getting initial data from the api
* `authentication`: _{
    publicKey: string
    identityToken?: string
  }_ - This stores information about the public key and user identity token
* `eventInfo`: EventInfo | null - information regarding the event as received from the api
* `timelineActions`: _ActionCall[] | null_ - list of mcls annotation action calls
* `error`: _notFound_ | _invalidPublicKey_ | _domainEmbedBlocked_ | _geoBlocked_ | _noEntitlement_ | _unexpectedError_ | _null_ - information regarding any errors that might occur when fetching events.
* `refetch`: _(updateId: string) => void_ - updates event information from api
* `refetchTimeline`: _(updateId: string) => void_ - updates timeline action calls from timeline api
* `activeView`: _VIDEO | UPCOMING | AUTHORIZATION | GEOBLOCKED | NOT_FOUND | LOADING | CONCURRENCY_LIMIT_
* `totalViewers`: string - number of active users

### `EventContextProvider`

This component handles the creation and management of the state for a single event.

Example of usage

```tsx
import { EventContextProvider, useEventState } from '@mycujoo/mcls-data-providers'

function EventPageWithContext() {
  return <EventContextProvider publicKey={"YOUR_PUBLIC_KEY"} eventId={"YOUR_EVENT_ID"} identityToken={"YOUR_IDENTITY_TOKEN"} >
    <EventPageInfo />
  </EventContextProvider>
}

const EventPageInfo = () => {
  const { isLoading, eventInfo, activeView} = useEventState()
  const eventMetadata = eventInfo.metadata

  const renderView = (view) => {
    switch (view) {
      case 'VIDEO':
        return 'render video player screen'
      case 'UPCOMING':
        return 'render upcoming screen'
      case  'AUTHORIZATION':
        return 'render ppv screen'
      case 'GEOBLOCKED':
        return 'render geoblocked screen'
      case 'NOT_FOUND':
        return 'render not found screen'
      case 'LOADING':
        return 'render loading screen'
      case 'CONCURRENCY_LIMIT':
        return 'render concurrency limit screen'
    }
      
  }

  return  eventInfo ? <div>
    <h1>{eventInfo.title}</h1>
    <p>{eventInfo.description}</p>
    <span>{eventMetadata.customEventTypeProp}</span>
    <div>network status: {isLoading? 'loading': 'loaded'}</div>
    <div>{renderView(activeView)}</div>
  </div> : null
}
```

Additional hooks for more granular state updates:

```tsx
const { timelineActions, isLoading } = useEventTimeline()
const refreshTimeline = useTimelineRefetch() // refreshTimeline()
const refreshEvent = useEventRefetch() // refreshEvent()
const isConcurrencyExceeded = useIsConcurrencyLimitExceeded()
const activeViewers = useEventTotalViewers()
const streamObject = useEventStream()
const source = useStreamSource()
const { metadata, isLoading } = useEventMetadata()
const authHeader = useAuthentication()
const { eventInfo, isLoading } = useEvent()
```

## Events list state

### `EventsContext`

This is a react context holding information about a list of events.

* `events`: _T[] / default []_ - list of event objects
* `loadMore`: _() => Promise\<void\>_ - loads more events to the current list if available
* `isLoading`: _boolean / default true_ - indicates if there's an active request to get the event list
* `debug`: _boolean / default false_ - logs events for debugging

### `EventsContextProvider`

This component handles the state creation and management for a list of events. This can be used in combination to [MCLS Slider](https://www.npmjs.com/package/@mycujoo/mcls-components-slider) or [MCLS Grid](https://www.npmjs.com/package/@mycujoo/mcls-components-grid) for various display options.

Example of usage

```tsx
import { EventsContextProvider, useEventsStore } from '@mycujoo/mcls-data-providers'
const refreshRateMs = 10 * 60 * 1000
const searchKey = ''
const eventReadMask = ['id', 'name', 'physical.coordinates', 'physical.continent_code']

type LightEventWithLocation = {
  id: string,
  name: string,
  physical: {
    coordinates: {
      latitude: number
      longiture: number
    },
    continent_code: string
  }
}

const EventsSection = () => {
    const filter = { 
      start_after_time: (startTime).toISOString(), 
      start_before_time: (endTime).toISOString(),
      status: ['EVENT_STATUS_SCHEDULED', 'EVENT_STATUS_STARTED'],
      continent_codes: ['EU', 'NA'],
      country_codes: ['NL', 'US'],
    }

    return <EventsContextProvider 
      publicKey={"YOUR_PUBLIC_KEY"} 
      orderBy="START_TIME_ASC" 
      pageSize={9}
      filter={filter}
      eventReadMask={eventReadMask}
      search={searchKey}
      refreshRateMs={refreshRateMs}
      debug
    >
        <CalendarSection  />
    </EventsContextProvider>
}

const CalendarSection = () => {
    const { events, isLoading, loadMore } = useEventsStore()
  
    return <div>
    {events && events.map((item: LightEventWithLocation) => (<div key={item.id}>
        <h1>{item.name}</h1>
        <div>longitude: {item.physical.coordinates?.longitude}</div>
        <div>latitude: {item.physical.coordinates?.latitude}</div>
      </div>))
    }
      <button onClick={() => { loadMore(false) }}>Load more</button>
    </div>
}

```

Additional hooks for more granular state updates:

```tsx
const useEvents = useEvents<CustomEventType>()
const loadMore = useLoadMoreEvents() // loadMore(isLoading); isLoading: boolean / default true - set to false if isLoading should not change when loading more   
const isLoading = useIsLoadingEvents()
```

### `useEventsList`

Hook for fetching event list data directly used internally by the context

Example of usage:

```tsx

import { useEventsList, buildKQLQuery } from '@mycujoo/mcls-data-providers'

const CustomEventList = () => {
  const { events: liveEvents, loadMore: loadMoreLive, isLoading: isLoadingLive } = useEventsList({
    publicKey: 'YOUR_PUBLIC_KEY',
    pageSize: 5,
    orderBy: 'START_TIME_DESC',
    filter: buildKQLQuery({
      country_codes: ['NL', 'US'],
      status: ['EVENT_STATUS_STARTED'],
    })
  })
  const { events: popularEvents, loadMore: loadMorePopular, isLoading: isLoadingPopular } = useEventsList({
    publicKey: 'YOUR_PUBLIC_KEY',
    pageSize: 3,
    orderBy: 'VIEWS_DESC',
    filter: buildKQLQuery({
      status: ['EVENT_STATUS_FINISHED'],
      'metadata.custom.nested.property': 'Your value'
    })
  })

  const { events: selectedEvents, isLoading: isLoadingPopular } = useEventsList({
    publicKey: 'YOUR_PUBLIC_KEY',
    featuredEventIds: ['TEST_EVENT_1', 'TEST_EVENT_2', 'TEST_EVENT_3']
  })


  ...
}

```

## Translation state

### `translate`

Utility funtion for translation common mcls terms:

Example of usage

```tsx
import { translate, SupportedLanguages } from '@mycujoo/mcls-data-providers'

const lang: SupportedLanguages = 'it'

console.log(translate('live', lang))
console.log(translate('Watch', lang))
console.log(translate('FullTime', lang))
```

## Packages state

### `EventPackagesContext`

This is a react context holding information about a list of event packages.

* `packages`: _Package[] / default []_ - list of event package objects
* `loadMore`: _() => Promise\<void\>_ - loads more event pacakge objects to the current list if available
* `isLoading`: _boolean / default true_ - indicates if there's an active request to get the event package list
* `isLimitReached`: _boolean / default false_ - indicates if there's more data to fetch (useful for pagination)
* `debug`: _boolean / default false_ - logs events for debugging

### `EventPackagesContextProvider`

This component handles the state creation and management for a list of event pacakges. This can be used in combination to [MCLS Slider](https://www.npmjs.com/package/@mycujoo/mcls-components-slider) or [MCLS Grid](https://www.npmjs.com/package/@mycujoo/mcls-components-grid) for various display options.

Example of usage

```tsx
import { EventPackagesContextProvider, useEventsStore } from '@mycujoo/mcls-data-providers'

const Paywall = () => {

    return <EventPackagesContextProvider 
      publicKey={publicKey} 
      identityToken={identityToken} 
      eventId={eventId}
    >
      <PaywallSlider />
    </EventPackagesContextProvider>
}

```

### `useEventPackages`

Hook for fetching event packages list data (used internally by the context)

Example of usage:

```tsx

import { useEventPackagesList } from '@mycujoo/mcls-data-providers'
import { Grid } from '@mycujoo/mcls-components-grid'

const CustomEventPackagesList = () => {
  const {
    packages,
    loadMore,
    createOrder,
    isLoading, 
    isLimitReached 
  } = useEventPackagesList({
    publicKey: 'YOUR_PUBLIC_KEY',
    identityToken: 'YOUR_USER_IDENTITY_TOKEN'
    pageSize: 5,
    refreshRateMs: 60000,
  })

  if (!isLoading) return null

  return  <Grid
      data={packages}
      title="Event packages"
      lang="es"
      onSeeAll={() => { console.log("On see all click") }}
      onLoadMore={loadMore}
      config={config}
      isLoading={isLoading}
      limitReached={limitReached}
      className="my-custom-grid"
      card={<PackageCard />}
      preloadCard={<PreloadCard />} 
      noDataContent={<NoContent />}
    />
}

```