Casl: Update on props change

Created on 23 Apr 2018  路  6Comments  路  Source: stalniy/casl

Hi,

I can't figure out what I am doing wrong. Can I show/hide UI element depending on object? here is some sample of code:

// ability.js
import { AbilityBuilder } from '@casl/ability'

function subjectName(item) {
  if (!item || typeof item === 'string') {
    return item
  }
  console.log('Type is:  ', item.__type);
  return item.__type
}

export default AbilityBuilder.define({ subjectName }, can => {
  can(['update', 'delete'], 'Account', { creator: 'John', role: 'Manager'})

})

then in my component I do:

import React, {Component} from 'react';
import Can from "./Can";

class MyComponent extends Component {
    state = {
        user: '',
        Perm: {
            creator: 'Jeff',
            role: 'Worker',
            __type: 'Account',
        }
    }

    clicked = () => {
        this.setState({Perm: {
            creator: 'John',
            role: 'Manager',
            __type: 'Account',
            }
        })
    }

    render () {
        console.log(this.state.Perm);
        return (
            <div>
                <h1>Permission</h1>
                <div>{this.state.Perm.creator}</div>

                <Can do='update' on={this.state.Perm}>
                   <button>Modify</button>
                </Can>


            <button onClick={this.clicked}>Change</button>
            </div>
        )
    }
}

export default MyComponent;

Jeff user indeed does get switched for John, so the component should be shown. I probably failed to understand something. The main reason why I am asking, is the fact that I will be getting roles from Redux, therefore I want to update my Navigation once user has logged in - depending on what role comes back from REST API

Appreciate any help!

bug

Most helpful comment

袛褍卸械 写褟泻褍褞!

Works as expected!!!

All 6 comments

Hi,

Could you please show what's inside ./Can file?

Of course:

import { createCanBoundTo } from '@casl/react';
import ability from '../config/ability';

export default createCanBoundTo(ability);

I see. I鈥檒l try to look at this today

This is a bug :) Thanks for raising this! I forgot to recheck abilities on property change. Will fix it soon

Fixed in @casl/[email protected]. Thanks for using CASL!

袛褍卸械 写褟泻褍褞!

Works as expected!!!

Was this page helpful?
0 / 5 - 0 ratings