Skip to content

Instantly share code, notes, and snippets.

@samarti
Created January 25, 2019 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samarti/2067b220b8f3ae5e3fb916dd49647a5f to your computer and use it in GitHub Desktop.
Save samarti/2067b220b8f3ae5e3fb916dd49647a5f to your computer and use it in GitHub Desktop.
import React from 'react';
import Checkbox from '@material-ui/core/Checkbox';
import { updatePermissions } from '../service';
class PermissionsForm extends React.Component {
constructor(props) {
super(props);
this.state = {
permissions: [],
loading: false,
error: '',
};
}
componentDidMount(props) {
// Traspasamos los permisos al estado para poder trabajar con ellos
const { permissions } = props;
this.setState({
permissions,
});
}
handlePermissionChange = permissionId => {
const auxPermissions = Object.assign([], this.state.permissions);
const auxP = auxPermissions.filter(p => p.id === permissionId)[0];
auxP.checked = !auxP.checked;
this.setState({
permissions: auxPermissions,
});
};
submitChanges = () => {
this.setState({ loading: true }, () => {
updatePermissions(options).then(
response => this.updatePermissionsSuccess(response),
error => this.updatePermissionsError(error),
);
});
};
updatePermissionsSuccess = () => {
this.setState({ loading: false });
// Notificar al usuario, mostrar un modal, un alert, un badge, etc.
};
updatePermissionsError = () => {
this.setState({ loading: true });
// Notificar al usuario, mostrar un modal, un alert, un badge, etc.
};
render() {
const { permissions } = this.state;
return (
<React.Fragment>
{permissions.map(p => (
<FormControlLabel
control={
<Checkbox
checked={p.checked}
onChange={this.handlePermissionChange(p.id)}
value={p.name}
/>
}
label={p.label}
/>
))}
<Button onClick={this.submitChanges()}>Guardar cambios</Button>
</React.Fragment>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment