Skip to content

Commit

Permalink
update readme (#469)
Browse files Browse the repository at this point in the history
  • Loading branch information
silesky authored May 24, 2022
1 parent 37382f1 commit 868901e
Show file tree
Hide file tree
Showing 11 changed files with 206 additions and 48 deletions.
4 changes: 2 additions & 2 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
},
"[javascriptreact]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescript]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
},
"[typescriptreact]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
}
127 changes: 88 additions & 39 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ Analytics Next (aka Analytics 2.0) is the latest version of Segment’s JavaScri
The easiest and quickest way to get started with Analytics 2.0 is to [use it through Segment](#-using-with-segment). Alternatively, you can [install it through NPM](#-using-as-an-npm-package) and do the instrumentation yourself.

## 💡 Using with Segment

1. Create a javascript source at [Segment](https://app.segment.com) - new sources will automatically be using Analytics 2.0! Segment will automatically generate a snippet that you can add to your website. For more information visit our [documentation](https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/)).

2. Start tracking!
Expand All @@ -30,7 +31,7 @@ The easiest and quickest way to get started with Analytics 2.0 is to [use it thr
1. Install the package

```sh
# npm
# npm
npm install @segment/analytics-next

# yarn
Expand All @@ -40,22 +41,91 @@ yarn add @segment/analytics-next
pnpm add @segment/analytics-next
```

2. Import the package into your project and you're good to go (with working types)!
2. Import the package into your project and you're good to go (with working types)!

```ts
import { AnalyticsBrowser } from '@segment/analytics-next'

const analytics = AnalyticsBrowser.load({ writeKey: '<YOUR_WRITE_KEY>' })

analytics.identify('hello world')

document.body?.addEventListener('click', () => {
analytics.track('document body clicked!')
})
```

### using `React` (Simple)

```tsx
import { AnalyticsBrowser } from '@segment/analytics-next'

// we can export this instance to share with rest of our codebase.
export const analytics = AnalyticsBrowser.load({ writeKey: '<YOUR_WRITE_KEY>' })

const App = () => (
<div>
<button onClick={() => analytics.track('hello world')}>Track</button>
</div>
)
```
import { Analytics, AnalyticsBrowser, Context } from '@segment/analytics-next'

async function loadAnalytics(): Promise<Analytics> {
const [ analytics, context ] = await AnalyticsBrowser.load({ writeKey })
return analytics
### using `React` (Advanced w/ React Context)

```tsx
import React from 'react'
import { AnalyticsBrowser } from '@segment/analytics-next'

const AnalyticsContext = React.createContext<AnalyticsBrowser>(undefined)

export const AnalyticsProvider: React.FC<{ writeKey: string }> = ({
children,
writeKey,
}) => {
const analytics = React.useMemo(
() => AnalyticsBrowser.load({ writeKey }),
[writeKey]
)
return (
<AnalyticsContext.Provider value={analytics}>
{children}
</AnalyticsContext.Provider>
)
}

// Create an analytics hook that we can use with other components.
export const useAnalytics = () => {
const result = React.useContext(AnalyticsContext)
if (!result) {
throw new Error('Context used outside of its Provider!')
}
return result
}

// use the context we just created...
const TrackButton = () => {
const analytics = useAnalytics()
return (
<button onClick={() => analytics.track('hello world').then(console.log)}>
Track!
</button>
)
}

const App = () => {
return (
<AnalyticsProvider writeKey='<YOUR_WRITE_KEY>'>
<TrackButton />
</AnalyticsProvider>
)
```
### using `React`
For another example,
There is a [React example repo](https://github.com/segmentio/react-example/) which outlines using the [Segment snippet](https://github.com/segmentio/react-example/tree/main/src/examples/analytics-quick-start) and using the [Segment npm package](https://github.com/segmentio/react-example/tree/main/src/examples/analytics-package).
### using `Vite` with `Vue 3`
1. add to your `index.html`
1. add to your `index.html`
```html
<script>
Expand All @@ -70,29 +140,12 @@ There is a [React example repo](https://github.com/segmentio/react-example/) whi
import { ref, reactive } from 'vue'
import { Analytics, AnalyticsBrowser } from '@segment/analytics-next'

const analytics = ref<Analytics>()

export const useSegment = () => {
if (!analytics.value) {
AnalyticsBrowser.load({
writeKey: '<YOUR_WRITE_KEY>',
})
.then(([response]) => {
analytics.value = response
})
.catch((e) => {
console.log('error loading segment')
})
}

return reactive({
analytics,
})
}

export const analytics = AnalyticsBrowser.load({
writeKey: '<YOUR_WRITE_KEY>',
})
```
3. in component
3. in component
```vue
<template>
Expand All @@ -101,26 +154,22 @@ export const useSegment = () => {

<script>
import { defineComponent } from 'vue'
import { useSegment } from './services/segment'
import { analytics } from './services/segment'

export default defineComponent({
setup() {
const { analytics } = useSegment()
function track() {
analytics?.track('Hello world')
function track() {
analytics.track('Hello world')
}

return {
track
track,
}
}
},
})
</script>
```


# 🐒 Development

First, clone the repo and then startup our local dev environment:
Expand Down
21 changes: 21 additions & 0 deletions example/context/analytics.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import React from 'react'
import { AnalyticsBrowser } from '../../'

const AnalyticsContext = React.createContext<AnalyticsBrowser>(undefined)

export const AnalyticsProvider: React.FC<{ writeKey: string }> = ({
children,
writeKey,
}) => {
const analytics = React.useMemo(
() => AnalyticsBrowser.load({ writeKey }),
[writeKey]
)
return (
<AnalyticsContext.Provider value={analytics}>
{children}
</AnalyticsContext.Provider>
)
}

export const useAnalytics = () => React.useContext(AnalyticsContext)
2 changes: 1 addition & 1 deletion example/next.config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE,
enabled: process.env.ANALYZE === 'true',
})

module.exports = withBundleAnalyzer({
Expand Down
6 changes: 2 additions & 4 deletions example/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
Analytics,
Context,
} from '../../'
import { useWriteKey } from '../utils/hooks/useWritekey'

const jsontheme = {
scheme: 'tomorrow',
Expand Down Expand Up @@ -44,10 +45,7 @@ export default function Home(): React.ReactElement {
AnalyticsBrowserSettings | undefined
>(undefined)
const [analyticsReady, setAnalyticsReady] = useState<boolean>(false)
const [writeKey, setWriteKey] = useLocalStorage(
'segment_playground_write_key',
''
)
const [writeKey, setWriteKey] = useWriteKey()
const [url, setURL] = useLocalStorage(
'segment_playground_cdn_url',
'https://cdn.segment.com'
Expand Down
33 changes: 33 additions & 0 deletions example/pages/vanilla/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import Link from 'next/link'
import { AnalyticsBrowser } from '../../../'

export const analytics = AnalyticsBrowser.load({
writeKey: process.env.NEXT_PUBLIC_WRITEKEY,
})

analytics.then(() => console.log('loaded!'))

const Vanilla: React.FC = () => {
analytics.identify('hello').then((res) => console.log('identified!', res))
return (
<div>
<input
style={{
display: 'block',
margin: '1rem 0',
}}
value="submit"
onClick={(e) => {
e.preventDefault()
analytics
.track('vanilla click')
.then((res) => console.log('tracked!', res))
}}
type="submit"
/>
<Link href={'/vanilla/other-page'}>Go to Other Page</Link>
</div>
)
}

export default Vanilla
30 changes: 30 additions & 0 deletions example/pages/vanilla/other-page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import Link from 'next/link'
import React, { useEffect } from 'react'
import { analytics } from '.'

const OtherPage: React.FC = () => {
useEffect(() => {
analytics.identify('hello').then((res) => console.log('identified!', res))
}, [])
return (
<div>
<input
style={{
display: 'block',
margin: '1rem 0',
}}
value="Track!"
onClick={(e) => {
e.preventDefault()
analytics
.track('clicked other page!')
.then((res) => console.log('tracked!', res))
}}
type="submit"
/>
<Link href={'/vanilla'}>Vanilla Home Link</Link>
</div>
)
}

export default OtherPage
20 changes: 20 additions & 0 deletions example/pages/with-context/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { AnalyticsProvider, useAnalytics } from '../../context/analytics'
import { useWriteKey } from '../../utils/hooks/useWritekey'

const App = () => {
const analytics = useAnalytics()
return (
<button onClick={() => analytics.track('hello world').then(console.log)}>
Track!
</button>
)
}

export default () => {
const [writeKey] = useWriteKey()
return (
<AnalyticsProvider writeKey={writeKey}>
<App />
</AnalyticsProvider>
)
}
2 changes: 1 addition & 1 deletion example/styles/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ body {

a {
color: inherit;
text-decoration: none;
text-decoration: underline;
}

* {
Expand Down
3 changes: 2 additions & 1 deletion example/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve"
"jsx": "preserve",
"incremental": true
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
Expand Down
6 changes: 6 additions & 0 deletions example/utils/hooks/useWritekey.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { useLocalStorage } from "./useLocalStorage";

export const useWriteKey = () => useLocalStorage(
'segment_playground_write_key',
process.env.NEXT_PUBLIC_WRITEKEY
)

0 comments on commit 868901e

Please sign in to comment.