This package aims to help users of React and React Native to use Dependency Injection (DI) and service pattern.
To use this you need the latest version of React, Node.js and npm/yarn.
git clone https://github.com/MurylloEx/react-use-service.git
cd react-use-service
npm install
npm start
Add the following lines in your tsconfig.json to enable experimental decorators and emit decorator metadata.
tsconfig.json
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
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>
);
}
Muryllo Pimenta – muryllo.pimenta@upe.br
Distribuído sobre a licença MIT. Veja LICENSE
para mais informações.
- 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