Using Endlinks in single page applications

If you use a single page application framework like React, Angular or Vue, and you have a server-side, the recommended approach is to use the api calls solution.

However if you have a Single Page App and need to use endlinks on browser, you can't rely on our widgets since technically everything lives in the same page. Instead you can use your application state to persist the token across pages as well as use localStorage, cookies or your database solution if you expect the completion of your flow to happen beyond this session.

For an example of how to use React Context to persist the token below. But you could as well use Redux or another state management solution.

Using React Context

For example using this React Context to wrap around your app, you can set and retrieve the token from different components:

React Context example

import React, { createContext, useState, useContext, useEffect } from 'react'

const EndlinkContext = createContext(null)

export function EndlinkTokenProvider({ children }) {
  const [endlinkToken, setEndlinkToken] = useState(null)

  useEffect(() => {
    console.log('Endlink token was set to', endlinkToken)
  }, [endlinkToken])

  return (
    <EndlinkContext.Provider value={{ endlinkToken, setEndlinkToken }}>
      {children}
    </EndlinkContext.Provider>
  )
}

export function useEndlinkToken() {
  const context = useContext(EndlinkContext)
  if (!context) {
    throw new Error(
      'useEndlinkToken must be used within a EndlinkTokenProvider',
    )
  }
  return context
}

Setting the token

On the component that loads in your landing url (the endlink url you added to the packet), you would set the token using the setEndlinkToken function from the hook in the context file_get_contents

Setting the token

const { endlinkToken, setEndlinkToken } = useEndlinkToken()

// Capture the token on mount
useEffect(() => {
  const searchParams = new URLSearchParams(window.location.search)
  const endlinkToken = searchParams.get('tartle_endlink_token') || null
  if (endlinkToken) {
    setEndlinkToken(endlinkToken)
  }
}, [])

Retrieving and using the token

Then later in the component that loads when your user has completed the flow you would retrieve the token and make the appropriate call to one of our Endlink endpoints.

Retrieving the token

const { endlinkToken } = useEndlinkToken()

// ...
// Later, you can make the api call depending on the outcome. 'GET' is implied but added for clarity.
const endlinkUrl = `https://source.tartle.co/api/v3/endlinks/complete?tartle_endlink_token=${endlinkToken}`
fetch(endlinkUrl, { method: 'GET' })

Was this page helpful?