mandajoan
mandajoan

Reputation: 13

How to use ES6 template literal in defining sessionStorage key

I am trying to use ES6 template literal syntax to set sessionStorage where part of the key is the active tab id.

I attempted first to put the ES6 template literal within the method:

sessionStorage.getItem(`tabContent + ${this.props.activeTabKey}`)

But this wouldn't compile.

I next created a constant within my method and then referred to it within the sessionStorage method:

//attempt 1
const activeTabSessionStorageName = `tabContent + ${this.props.activeTabKey}`
(sessionStorage.getItem(`${activeTabSessionStorageName}`))

// attempt 2

const activeTabSessionStorageName = `tabContent + ${this.props.activeTabKey}`

  sessionStorage.getItem(JSON.stringify(activeTabSessionStorageName))

//attempt 3
const activeTabSessionStorageName = `tabContent + ${this.props.activeTabKey}`
(sessionStorage.getItem(this.activeTabSessionStorageName))

I am not sure what would be the correct syntax but both failed and came up with the error:

 SyntaxError: Unexpected token u in JSON at position 0

My goal is to have a way to dynamically check the storage to see if they key exists and then set it if not.

I am not that familiar with sessionStorage other than high level understanding. I know the key and the value have to be strings.

I am using React and Redux

Upvotes: 1

Views: 318

Answers (1)

Arman Charan
Arman Charan

Reputation: 5797

Your error is likely a result of attempting to JSON.parse() an undefined value.

window.sessionStorage can be combined with JSON.stringify() and JSON.parse() to commit data for sessions.

See below for a practical example, including Template Literals and a safe escape for cases when no sessionStorage Item is found.

// Hypothetical Object.
const hypotheticalObject = {
  id: 'unique id',
  data: 'data ..'
}

// Set Object to Session Storage.
window.sessionStorage.setItem(`CONTENT + ${hypotheticalObject.id}`, JSON.stringify(hypotheticalObject))

// Get Object.
const retrievedObject = window.sessionStorage.getItem(`CONTENT + ${hypotheticalObject.id}`) && JSON.parse(window.sessionStorage.getItem(`CONTENT + ${hypotheticalObject.id}`)) || false

// Log.
console.log(retrievedObject)

Upvotes: 1

Related Questions