I ran into issues around pg. 37 related to stimulus targets with the following console error:
day_toggle_controller.ts:6 Uncaught (in promise) TypeError: Cannot set property thingToHideTarget of # which has only a getter
I also noticed that the book src code dir stimulus/03 doesn’t work (click hide has no effect), but stimulus/04 does work. This leads me to believe the issue is related to targets but I haven’t done a thorough analysis. I’m not sure if this is likely to be versioning issues or what but it might be useful for anyone else trying to work through the book.
2 Likes
This error is related to the Webpacker and Babel setup that changed in Webpacker 5.1, so it is related to targets in that targets cause the static
elements to be used and the Babel setup has some trouble with that language feature.
it’s possible that some of the directories in the sample code weren’t updated properly, I’ll take a look.
Thanks!
1 Like
This might be a change in how the released version of Stimulus 2.0 handles implicit properties, but I was getting the same error on line 6. Just removing the line with the property declaration caused the code to work.
// app/javascripts/controllers/day_toggle_controller.ts
import { Controller } from "stimulus"
export default class DayToggleController extends Controller {
static targets = ["thingToHide"]
// This was the offending line. Was expecting a different error when commented out, but it worked
// thingToHideTarget: HTMLElement
toggle() {
console.log('Click! Click! Boom!')
this.thingToHideTarget.classList.toggle("is-hidden")
}
}
I’m only on page 37 and don’t know Typescript or Stimulus, so I don’t know if this will cause problems later on.
1 Like
Oddly enough, it became unbroken after I added in the hiddenClass.
// this now works and I don't understand why
import { Controller } from "stimulus"
export default class DayToggleController extends Controller {
static classes = ["hidden"]
static targets = ["thingToHide"]
hiddenClass: string
thingToHideTarget: HTMLElement // ??? doesn't error out now
toggle() {
console.log('Click! Click! Boom!')
this.thingToHideTarget.classList.toggle(this.hiddenClass)
}
}