adamdickinson / react-service Goto Github PK
View Code? Open in Web Editor NEWExpose internal application APIs as a service.
Expose internal application APIs as a service.
When calling the hook returned from createService
in a component that is not sitting under the service provider the return value of the hook will be undefined
.
This makes absolute sense to me (rather than the hook throwing an error for example) and is how vanilla react context works. It's actually ideal because I have components that can be used inside or outside of a service provider, leveraging the service only if they are in its provider.
The only issue is the return type of the hook states it will always return a value, when in reality it can return undefined
.
Even if we believe most of the time the hook will return a truthy value, I would prefer we be accurate.
This would be a design-time breaking change for anyone with strict null checking enabled, forcing those consumers to change their code slightly.
Contrived Example:
const LogoutButton = () => {
const { logout } = useAuth() // If consumer has
return <button onClick={logout}>Logout</button>
}
Might need to become something like
const LogoutButton = () => {
const { logout } = useAuth() ?? {}
return <button onClick={logout}>Logout</button>
}
Or if they are lazy
const LogoutButton = () => {
const { logout } = useAuth()!
return <button onClick={logout}>Logout</button>
}
Or they can be smarter by not rendering the component/rendering it differently if the api isn't provided, etc.
Or if you want to keep the usage simple for consumers who will always define their consuming components within their service providers, then we could offer a way to get a hook for the service that always returns a truthy value or throws an error if the service is not provided.
Thoughts @adamdickinson?
I was looking over the documentation to refresh myself on usage and I noticed something that didn't look right.
// 1. We define the service
const [NumberProvider, useNumber] = createService(({ max: number }) => {
const [number, setNumber] = useState<number>()
return {
update: () => setNumber(Math.floor(Math.random() * max)),
number,
}
})
I think ({ max: number }) => {
is meant to be ({ max }: { max: number }) => {
.
It looks like the subtle mistake is repeated in the Auth example: const useAuthAPI = ({ serverUrl: string }) => {
When fixing this it would be good to test those entire code snippets to ensure they're correct.
master
branch failed. π¨I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.
You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. Iβm sure you can fix this πͺ.
Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.
Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master
branch. You can also manually restart the failed CI job that runs semantic-release.
If you are not sure how to resolve this, here are some links that can help you:
If those donβt help, or if this issue is reporting something you think isnβt right, you can always ask the humans behind semantic-release.
An npm token must be created and set in the NPM_TOKEN
environment variable on your CI environment.
Please make sure to create an npm token and to set it in the NPM_TOKEN
environment variable on your CI environment. The token must allow to publish to the registry https://registry.npmjs.org/
.
Good luck with your project β¨
Your semantic-release bot π¦π
As mentioned in the README, having many services offered by an app gets a bit intense. Because of how context works, it means we'd be looking at a lot of top-level nesting.
There is another possible option however - shared context.
The best APIs are designed for those who use them, not those who build them, so it's worth looking at how we might like to apply a single-provider service structure:
import { Services } from '@adamdickinson/react-service'
import { AuthService } from './services/auth'
import { NoticeService } from './services/notice'
import { ReportService } from './services/report'
const App = () => (
<Services services={[AuthService, NoticeService, ReportService]}>
...
</Services>
)
import { useAuth } from './services/auth'
const SubComponent = () => {
const { user } = useAuth()
return <h1>{user?.name ?? 'Not logged in'}</h1>
}
And if we wanted to, we should be able to expose services at various points in our app:
const App = () => (
<>
<Services auth={AuthService}>
<Services report={ReportService}>
...
</Services>
</Services>
<Services notice={NoticeService}>
...
</Services>
</>
)
The smarter way to handle this would be as follows, but the above illustrates being able to expose many services with only a few providers well:
const App = () => (
<>
<AuthService>
<ReportService>
...
</ReportService>
</AuthService>
<NoticeService>
...
</NoticeService>
</>
)
A single context seems to be the way...
const ServiceContext = React.createContext()
interface ServicesProps {
services: Service[]
}
const Services = ({ children, ...services }) => {
const existingApis = useContext(ServiceContext)
const apis = {
// Carry forward higher-level services
...existingApis
// Add newly defined services
...Object.keys(services).reduce((newApis, name) => {
apis[name] = services[name].useApi()
}, newApis)
}
return (
<ServiceContext.Provider value={apis}>
{children}
</ServiceContext.Provider>
)
}
The simple benefit is that we can now throw in a heap of services without a nesting nightmare, but we could do that without many architectural changes, so why does the above proposal attempt to wrap everything in a single context? Because it allows us to get services talking to each other. Let's say you have a Data service that uses Auth info, and an Auth service that will make use of unauthorised processes in the Data service - this structure will allow us to do this.
More thoughts on the way on this one.
I'm looking to export two service providers from one package - one to handle a normal service, one to handle the mocked variation. Trouble is, both would need to use the same context in order to enable reuse of existing parts throughout the code. That is, I want to be able to switch the provider <MyService>
with a mocked version <MyMockedService>
.
I'm thinking the following workflow would work well:
const [MyService, useMyService, MyServiceContext] = createService(useMyServiceApi);
const MyMockedService = extendService(MyServiceContext, useMyMockedServiceApi);
They would essentially be the same process, differing only in whether context is provided or created. Alternatively, we could just re-use createService in these ways:
// createService(hook, context?) => [ServiceProvider, ServiceHook];
const [MyService, useMyService, MyServiceContext] = createService(useMyServiceApi);
const MyMockedService = createService(useMyMockedServiceApi, MyServiceContext);
// createServices(hookA, hookB, ...) => [ServiceProviderA, ServiceProviderB, ..., ServiceHook];
const [MyService, MyMockedService, useMyService] = createServices(useMyServiceApi, useMyMockedServiceApi);
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.