-
Notifications
You must be signed in to change notification settings - Fork 4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add solid-jotai-x
#16
Draft
rtritto
wants to merge
3
commits into
udecode:main
Choose a base branch
from
rtritto:solid-jotai-x-init
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,885
−0
Draft
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
__tests__ | ||
__test-utils__ | ||
__mocks__ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
# jotai-x | ||
|
||
## 1.2.4 | ||
|
||
### Patch Changes | ||
|
||
- [`24a1de7`](https://github.com/udecode/jotai-x/commit/24a1de747cea2ecc89b3005877527a7805a0eb87) by [@zbeyens](https://github.com/zbeyens) – doc | ||
|
||
## 1.2.3 | ||
|
||
### Patch Changes | ||
|
||
- [#11](https://github.com/udecode/jotai-x/pull/11) by [@12joan](https://github.com/12joan) – Do not render jotai's Provider component as part of jotai-x's provider. Jotai's Provider is unnecessary and interferes with vanilla jotai atoms. | ||
|
||
- [#13](https://github.com/udecode/jotai-x/pull/13) by [@zbeyens](https://github.com/zbeyens) – use client in createAtomProvider | ||
|
||
## 1.2.2 | ||
|
||
### Patch Changes | ||
|
||
- [#8](https://github.com/udecode/jotai-x/pull/8) by [@zbeyens](https://github.com/zbeyens) – Fix React imports for SSR | ||
|
||
## 1.2.1 | ||
|
||
### Patch Changes | ||
|
||
- [#6](https://github.com/udecode/jotai-x/pull/6) by [@12joan](https://github.com/12joan) – Fix: Provider prop types expect atoms instead of values for stores created with custom atoms | ||
|
||
## 1.2.0 | ||
|
||
### Minor Changes | ||
|
||
- [#4](https://github.com/udecode/jotai-x/pull/4) by [@12joan](https://github.com/12joan) – Add `warnIfNoStore` option to `UseAtomOptions` | ||
|
||
## 1.1.0 | ||
|
||
### Minor Changes | ||
|
||
- [#2](https://github.com/udecode/jotai-x/pull/2) by [@12joan](https://github.com/12joan) – | ||
- Atoms other than `atom` can now be passed in the `initialState` argument to `createAtomStore`. Primitive values use `atom` by default | ||
- Added an `extend` option to `createAtomStore` that lets you add derived atoms to the store | ||
- New accessors on `UseStoreApi` | ||
- `useMyStore().store()` returns the `JotaiStore` for the current context, or undefined if no store exists | ||
- `useMyStore().{get,set,use}.atom(someAtom)` accesses `someAtom` through the store | ||
- Types: remove exports for some internal types | ||
- `GetRecord` | ||
- `SetRecord` | ||
- `UseRecord` | ||
|
||
## 1.0.1 | ||
|
||
### Patch Changes | ||
|
||
- [`099d310`](https://github.com/udecode/jotai-x/commit/099d310cdec35767aeaa2616634cb2502ccbc5e7) by [@zbeyens](https://github.com/zbeyens) – Fix: add React as peer dependency. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,253 @@ | ||
# JotaiX | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Needs to be adapted |
||
|
||
JotaiX is a custom extension of [Jotai](https://github.com/pmndrs/jotai), a primitive and flexible state management library for React. Jotai offers a | ||
minimalistic API to manage global, derived, or async states in React, solving common issues such as unnecessary | ||
re-renders or complex context management. JotaiX builds upon this foundation, providing enhanced utilities and patterns | ||
for more efficient and streamlined state management in larger and more complex applications. | ||
|
||
`jotai-x`, built on top of `jotai`, is providing a powerful store factory | ||
which solves these challenges, so you can focus on your app. | ||
|
||
```bash | ||
yarn add jotai jotai-x | ||
``` | ||
|
||
For further details and API documentation, visit [jotai-x.udecode.dev](https://jotai-x.udecode.dev). | ||
|
||
## **Why Choose `jotai-x`?** | ||
|
||
- Reduces boilerplate: Simplifies state management with concise and powerful utilities. | ||
- Enhanced modular state management: Offers advanced features like atom stores, hydration utilities, and more. | ||
- Improved developer experience: Strong TypeScript support ensures type safety and better developer tooling. | ||
- Seamless integration with Jotai: Builds on top of Jotai's API, making it easy for existing Jotai users to adopt. | ||
|
||
## **Core Features** | ||
|
||
### **Creating a Store** | ||
|
||
JotaiX allows for the creation of structured stores with ease, integrating seamlessly with Jotai's atom concept. | ||
|
||
```tsx | ||
import { createAtomStore } from 'jotai-x'; | ||
|
||
// Notice how it uses the name of the store in the returned object. | ||
export const { useElementStore, ElementProvider } = createAtomStore({ | ||
element: null | ||
}, { | ||
name: 'element' | ||
}); | ||
``` | ||
|
||
The **`createAtomStore`** function simplifies the process of creating and managing atom-based states. | ||
|
||
#### Function Signature | ||
|
||
```tsx | ||
createAtomStore<T extends object>(initialState: T, options?: CreateAtomStoreOptions): AtomStoreApi; | ||
``` | ||
|
||
- **`initialState`**: This is an object representing the initial state of your store. Each key-value pair in this object is used to create an individual atom. This is required even if you want to set the initial value from the provider, otherwise the atom would not be created. | ||
- **`options`**: Optional. This parameter allows you to pass additional configuration options for the store creation. | ||
|
||
#### Options | ||
|
||
The **`options`** object can include several properties to customize the behavior of your store: | ||
|
||
- **`name`**: A string representing the name of the store, which can be helpful for debugging or when working with multiple stores. | ||
- **`delay`**: If you need to introduce a delay in state updates, you can specify it here. Optional. | ||
- **`effect`**: A React component that can be used to run effects inside the provider. Optional. | ||
- **`extend`**: Extend the store with derived atoms based on the store state. Optional. | ||
|
||
#### Return Value | ||
|
||
The **`createAtomStore`** function returns an object (**`AtomStoreApi`**) containing the following properties and methods for interacting with the store: | ||
|
||
- **`use<Name>Store`**: | ||
- A function that returns the following objects: **`get`**, **`set`**, **`use`** and **`store`**, where values are hooks for each state defined in the store. | ||
- **`get`**: Hooks for accessing a state within a component, ensuring re-rendering when the state changes. See [useAtomValue](https://jotai.org/docs/core/use-atom#useatomvalue). | ||
- **`set`**: Hooks for setting a state within a component. See [useSetAtom](https://jotai.org/docs/core/use-atom#usesetatom). | ||
- **`use`**: Hooks for accessing and setting a state within a component, ensuring re-rendering when the state changes. See [useAtom](https://jotai.org/docs/core/use-atom). | ||
- **`store`**: A hook to access the [JotaiStore](https://jotai.org/docs/core/store) for the current context. | ||
- Example: `const [element, setElement] = useElementStore().use.element()` | ||
- **`<Name>Provider`**: | ||
- The API includes dynamically generated provider components for each defined store. This allows scoped state management within your application. More information in the next section. | ||
- **`<name>Store`**: | ||
- **`atom`**: Access the atoms used by the store, including derived atoms defined using `extend`. See [atom](https://jotai.org/docs/core/atom). | ||
|
||
### **Provider-Based Store Hydration and Synchronization** | ||
|
||
**`createAtomStore`** generates a provider component (`<Name>Provider`) for a Jotai store. This provider not only supplies the store to its child components but also handles hydrating and syncing the store's state. Here's how it works: | ||
|
||
- **Hydration**: Hydrates atoms with initial values. It's particularly useful for SSR, ensuring that the client-side state aligns with what was rendered on the server. Use `initialValues` prop. | ||
- **Synchronization**: Updates atoms with new values as external changes occur, maintaining consistency across the application. Use `<state>` props: there is one for each state defined in the store. | ||
|
||
### Scoped Providers and Context Management | ||
|
||
JotaiX creates scoped providers, enabling more granular control over different segments of state within your application. `createAtomStore` sets up a context for each store, which can be scoped using the **`scope`** prop. This is particularly beneficial in complex applications where nested providers are needed. | ||
|
||
### Derived Atoms | ||
|
||
There are two ways of creating derived atoms from your JotaiX store. | ||
|
||
#### Derived Atoms Using `extend` | ||
|
||
Atoms defined using the `extend` option are made available in the same places as other values in the store. | ||
|
||
```ts | ||
const { useUserStore } = createAtomStore({ | ||
username: 'Alice', | ||
}, { | ||
name: 'user', | ||
extend: (atoms) => ({ | ||
intro: atom((get) => `My name is ${get(atoms.username)}`), | ||
}), | ||
}); | ||
|
||
const intro = useAppStore().get.intro(); | ||
``` | ||
|
||
#### Externally Defined Derived Atoms | ||
|
||
Derived atoms can also be defined externally by accessing the store's atoms through the `<name>Store` API. Externally defined atoms can be accessed through the store using the special `use<Name>Store().{get,set,use}.atom` hooks. | ||
|
||
```ts | ||
const { userStore, useUserStore } = createAtomStore({ | ||
username: 'Alice', | ||
}, { name: 'user' }); | ||
|
||
const introAtom = atom((get) => `My name is ${get(userStore.atom.username)}`); | ||
const intro = useUserStore().get.atom(introAtom); | ||
``` | ||
|
||
### Example Usage | ||
|
||
#### 1. Create a store | ||
|
||
```tsx | ||
import { createAtomStore } from 'jotai-x'; | ||
|
||
export type AppStore = { | ||
name: string; | ||
onUpdateName: (name: string) => void; | ||
}; | ||
|
||
const initialState: Nullable<AppStore> = { | ||
name: null, | ||
onUpdateName: null, | ||
}; | ||
|
||
export const { useAppStore, AppProvider } = createAtomStore( | ||
initialState as AppStore, | ||
{ name: 'app' } | ||
); | ||
``` | ||
|
||
#### 2. Use the store in a component | ||
|
||
```tsx | ||
// ... | ||
|
||
const App = () => { | ||
return ( | ||
<AppProvider | ||
initialValues={{ | ||
onUpdateName: (name: string) => console.log(name) | ||
}} | ||
// Either here or in initialValues | ||
name="John Doe" | ||
> | ||
<Component /> | ||
</AppProvider> | ||
); | ||
}; | ||
|
||
const Component = () => { | ||
const [name, setName] = useAppStore().use.name(); | ||
const onUpdateName = useAppStore().get.onUpdateName(); | ||
|
||
return ( | ||
<div> | ||
<input value={name} onChange={(e) => setName(e.target.value)} /> | ||
<button onClick={() => onUpdateName(name)}>Update</button> | ||
</div> | ||
); | ||
}; | ||
``` | ||
|
||
#### Scoped Providers | ||
|
||
```tsx | ||
const App = () => { | ||
return ( | ||
// Parent scope | ||
<AppProvider | ||
scope="parent" | ||
initialValues={{ | ||
onUpdateName: (name: string) => console.log("Parent:", name) | ||
}} | ||
name="Parent User" | ||
> | ||
<div> | ||
<h1>Parent Component</h1> | ||
<Component /> | ||
{/* Child scope */} | ||
<AppProvider | ||
scope="child" | ||
initialValues={{ | ||
onUpdateName: (name: string) => console.log("Child:", name) | ||
}} | ||
name="Child User" | ||
> | ||
<div> | ||
<h2>Child Component</h2> | ||
<Component /> | ||
</div> | ||
</AppProvider> | ||
</div> | ||
</AppProvider> | ||
); | ||
}; | ||
|
||
// Accessing state from the specified scope. | ||
const Component = () => { | ||
// Here, we get the state from the parent scope | ||
const [name, setName] = useAppStore('parent').use.name(); | ||
// Here, we get the state from the closest scope (default) | ||
const onUpdateName = useAppStore().get.onUpdateName(); | ||
|
||
return ( | ||
<div> | ||
<input value={name || ''} onChange={(e) => setName(e.target.value)} /> | ||
<button onClick={() => onUpdateName(name)}>Update Name</button> | ||
</div> | ||
); | ||
}; | ||
``` | ||
|
||
## Contributing | ||
|
||
### Ideas and discussions | ||
|
||
[Discussions](https://github.com/udecode/jotai-x/discussions) is the best | ||
place for bringing opinions and contributions. Letting us know if we're | ||
going in the right or wrong direction is great feedback and will be much | ||
appreciated! | ||
|
||
#### [Become a Sponsor!](https://github.com/sponsors/zbeyens) | ||
|
||
### Contributors | ||
|
||
🌟 Stars and 📥 Pull requests are welcome! Don't hesitate to **share | ||
your feedback** here. Read our | ||
[contributing guide](https://github.com/udecode/jotai-x/blob/main/CONTRIBUTING.md) | ||
to get started. | ||
|
||
<p> | ||
<a href="https://www.netlify.com"> | ||
<img src="https://www.netlify.com/img/global/badges/netlify-color-accent.svg" alt="Deploys by Netlify" /> | ||
</a> | ||
</p> | ||
|
||
## License | ||
|
||
[MIT](https://github.com/udecode/jotai-x/blob/main/LICENSE) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
{ | ||
"name": "solid-jotai-x", | ||
"version": "1.0.0", | ||
"description": "Jotai store factory for a best-in-class developer experience.", | ||
"license": "MIT", | ||
"homepage": "https://jotai-x.udecode.dev/", | ||
"repository": { | ||
"type": "git", | ||
"url": "https://github.com/udecode/jotai-x.git", | ||
"directory": "packages/solid-jotai-x" | ||
}, | ||
"bugs": { | ||
"url": "https://github.com/udecode/jotai-x/issues" | ||
}, | ||
"sideEffects": false, | ||
"main": "dist/index.js", | ||
"module": "dist/index.mjs", | ||
"types": "dist/index.d.ts", | ||
"files": [ | ||
"dist/**/*" | ||
], | ||
"exports": { | ||
".": { | ||
"types": "./dist/index.d.ts", | ||
"import": "./dist/index.mjs", | ||
"module": "./dist/index.mjs", | ||
"require": "./dist/index.js" | ||
} | ||
}, | ||
"scripts": { | ||
"build": "yarn p:build", | ||
"build:watch": "yarn p:build:watch", | ||
"brl": "yarn p:brl", | ||
"clean": "yarn p:clean", | ||
"lint": "yarn p:lint", | ||
"lint:fix": "yarn p:lint:fix", | ||
"test": "yarn p:test", | ||
"test:watch": "yarn p:test:watch", | ||
"typecheck": "yarn p:typecheck" | ||
}, | ||
"peerDependencies": { | ||
"jotai": ">=2", | ||
"solid-jotai": ">=0", | ||
"solid-js": ">=1" | ||
}, | ||
"keywords": [ | ||
"jotai", | ||
"solid-jotai" | ||
], | ||
"publishConfig": { | ||
"access": "public" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
import { atom } from 'solid-jotai'; | ||
|
||
import type { WritableAtom } from 'jotai/vanilla'; | ||
|
||
type WrapFn<T> = T extends (...args: infer _A) => infer _R ? { __fn: T } : T; | ||
|
||
const wrapFn = <T>(fnOrValue: T): WrapFn<T> => | ||
(typeof fnOrValue === 'function' ? { __fn: fnOrValue } : fnOrValue) as any; | ||
|
||
type UnwrapFn<T> = T extends { __fn: infer U } ? U : T; | ||
|
||
const unwrapFn = <T>(wrappedFnOrValue: T): UnwrapFn<T> => | ||
(wrappedFnOrValue && | ||
typeof wrappedFnOrValue === 'object' && | ||
'__fn' in wrappedFnOrValue | ||
? wrappedFnOrValue.__fn | ||
: wrappedFnOrValue) as any; | ||
|
||
/** | ||
* Jotai atoms don't allow functions as values by default. This function is a | ||
* drop-in replacement for `atom` that wraps functions in an object while | ||
* leaving non-functions unchanged. The wrapper object should be completely | ||
* invisible to consumers of the atom. | ||
*/ | ||
export const atomWithFn = <T>(initialValue: T): WritableAtom<T, [T], void> => { | ||
const baseAtom = atom(wrapFn(initialValue)); | ||
|
||
return atom( | ||
(get) => unwrapFn(get(baseAtom)) as T, | ||
(_get, set, value) => set(baseAtom, wrapFn(value)) | ||
); | ||
}; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
File can be removed