stalniy / casl

CASL is an isomorphic authorization JavaScript library which restricts what resources a given user is allowed to access
https://casl.js.org/
MIT License
5.93k stars 269 forks source link

Destructuring context triggers TypeError: Cannot read property 'relevantRuleFor' of undefined #462

Closed jzecca closed 3 years ago

jzecca commented 3 years ago

Using destructuring on CASL React context fails with the following error:

TypeError: Cannot read property 'relevantRuleFor' of undefined

To Reproduce

// Working
const ability = useContext(AbilityContext);
console.log(ability.can('read', 'something'));

// Failing
const { can } = useContext(AbilityContext);
console.log(can('read', 'something'));

Expected behavior I expected this to work, obviously. For the sake of readability, I'd really prefer to call can() rather than ability.can() in my components.

Interactive example Here's a reproducer : just change export default Test1 to export default Test2 on L23.


This took me forever to figure out, as I didn't (and still don't) see any reason for this to fail. Am I missing something here?

Thanks in advance!

EDIT: I think this might be the reason for issue #407

stalniy commented 3 years ago

This is solvable in userland just bind can and whatever properties you want to provided Ability instance. This is what I did in one of the casl-examples

stalniy commented 3 years ago

I close this as I don't plan to change the behavior at least for now. But feel free to express your thoughts here

jzecca commented 3 years ago

Binding can & cannot did the trick. Thanks a lot!