react-use-service
v0.1.8
Published
This package aims to help users of React and React Native to use Dependency Injection (DI) and Service Pattern.
Maintainers
Readme
To use this you need the latest version of React, Node.js and npm/yarn.
Installation
git clone https://github.com/MurylloEx/react-use-service.git
cd react-use-service
npm install
npm startAdd the following lines in your tsconfig.json to enable experimental decorators and emit decorator metadata.
tsconfig.json
"experimentalDecorators": true,
"emitDecoratorMetadata": true,Example
services.ts
@Service()
export class DatabaseService {
constructor() {}
insert(table: string, data: { [column: string]: string | number }) {
console.log(`writing to ${table}:`);
console.log(data);
}
}
@Service()
export class MyLoggerService {
constructor(private dbService: DatabaseService) {}
info(message: string) {
this.dbService.insert('log', {
level: 200,
message: message
});
}
}
@Service()
export class UserService {
constructor(private logger: MyLoggerService) {}
editUser(userId: number) {
this.logger.info(`User ${userId} has been edited`);
}
}index.tsx
const Container = ServiceContainer.create().providers([
DatabaseService,
MyLoggerService,
UserService
]);
ReactDOM.render(
<ServiceProvider container={Container}>
<App />
</ServiceProvider>,
document.getElementById('root')
);App.tsx
export function App() {
const user = useService<UserService>(UserService);
useEffect(() => {
user.editUser(3);
}, [user]);
return (
<p>Hello world!</p>
);
}Metadata
Muryllo Pimenta – [email protected]Distribuído sobre a licença MIT. Veja LICENSE para mais informações.
Contributing
- Fork it (https://github.com/MurylloEx/react-use-service/fork)
- Create your feature branch (
git checkout -b feature/fooBar) - Commit your changes (
git commit -am 'Add some fooBar') - Push to the branch (
git push origin feature/fooBar) - Create a new Pull Request
