-
Notifications
You must be signed in to change notification settings - Fork 278
docs: add jotai to cookbook #1634
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
Merged
Merged
Changes from 2 commits
Commits
Show all changes
4 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 hidden or 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,43 @@ | ||
import * as React from 'react'; | ||
import { render, screen, userEvent } from '@testing-library/react-native'; | ||
import { addTodo, getTodos, store, TodoItem, TodoList, todosAtom } from './TodoList'; | ||
import { renderWithAtoms } from './test-utils'; | ||
|
||
jest.useFakeTimers(); | ||
test('renders an empty to do list', () => { | ||
render(<TodoList />); | ||
expect(screen.getByText(/no todos, start by adding one/i)).toBeOnTheScreen(); | ||
}); | ||
|
||
const INITIAL_TODOS: TodoItem[] = [{ id: '1', text: 'Buy bread' }]; | ||
|
||
test('renders a to do list with 1 items initially, and adds a new item', async () => { | ||
renderWithAtoms<TodoItem[]>(<TodoList />, { | ||
initialValues: [ | ||
[todosAtom, INITIAL_TODOS], | ||
// optional: add any other Jotai atoms and their corresponding initial values | ||
], | ||
}); | ||
expect(screen.getByText(/buy bread/i)).toBeOnTheScreen(); | ||
expect(screen.getAllByLabelText('todo-item')).toHaveLength(1); | ||
|
||
const user = userEvent.setup(); | ||
const addTodoButton = screen.getByRole('button', { name: /add a random to-do/i }); | ||
await user.press(addTodoButton); | ||
|
||
expect(screen.getByText(/buy almond milk/i)).toBeOnTheScreen(); | ||
expect(screen.getAllByLabelText('todo-item')).toHaveLength(2); | ||
}); | ||
|
||
test("[outside react's scope]start with 1 initial todo and adds a new todo item", () => { | ||
// Set the initial to do items in the store | ||
store.set(todosAtom, INITIAL_TODOS); | ||
|
||
expect(getTodos()).toEqual(INITIAL_TODOS); | ||
const NEW_TODO = { id: '2', text: 'Buy almond milk' }; | ||
addTodo({ | ||
id: '2', | ||
text: 'Buy almond milk', | ||
}); | ||
expect(getTodos()).toEqual([...INITIAL_TODOS, NEW_TODO]); | ||
}); |
This file contains hidden or 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,51 @@ | ||
import * as React from 'react'; | ||
import { FlatList, Pressable, Text, View } from 'react-native'; | ||
import { atom, createStore, useAtom } from 'jotai'; | ||
|
||
export type TodoItem = { | ||
id: string; | ||
text: string; | ||
}; | ||
|
||
export const todosAtom = atom<TodoItem[]>([]); | ||
|
||
export function TodoList() { | ||
const [todos, setTodos] = useAtom(todosAtom); | ||
|
||
const handleAddTodo = () => | ||
setTodos((prev) => [ | ||
...prev, | ||
{ | ||
id: Math.random().toString(36).slice(2, 11), | ||
text: 'Buy almond milk', | ||
}, | ||
]); | ||
|
||
if (!todos.length) { | ||
return <Text>No todos, start by adding one...</Text>; | ||
} | ||
|
||
return ( | ||
<View> | ||
<FlatList | ||
data={todos} | ||
renderItem={({ item }: { item: TodoItem }) => ( | ||
<Text key={item.id} accessibilityLabel={'todo-item'}> | ||
vanGalilea marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{item.text} | ||
</Text> | ||
)} | ||
/> | ||
<Pressable accessibilityRole="button" onPress={handleAddTodo}> | ||
<Text>Add a random to-do</Text> | ||
</Pressable> | ||
</View> | ||
); | ||
} | ||
|
||
// Available for use outside react components | ||
vanGalilea marked this conversation as resolved.
Show resolved
Hide resolved
|
||
export const store = createStore(); | ||
export const getTodos = (): TodoItem[] => store.get(todosAtom); | ||
export const addTodo = (newTodo: TodoItem) => { | ||
const todos = getTodos(); | ||
store.set(todosAtom, [...todos, newTodo]); | ||
}; |
This file contains hidden or 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,35 @@ | ||
import * as React from 'react'; | ||
import {render} from '@testing-library/react-native'; | ||
import {useHydrateAtoms} from "jotai/utils"; | ||
import {IHydrateAtomsProps, InitialValues, IRenderWithAtomsOptions} from "./types"; | ||
|
||
function HydrateAtomsWrapper<T>({ | ||
initialValues, | ||
children, | ||
}: IHydrateAtomsProps<T>) { | ||
useHydrateAtoms(initialValues as unknown as InitialValues); | ||
return children; | ||
} | ||
|
||
/** | ||
* Renders a React component with Jotai atoms for testing purposes. | ||
* | ||
* @template T - The type of the initial values for the atoms. | ||
* @param component - The React component to render. | ||
* @param options - The render options including the initial atom values. | ||
* @returns The render result from `@testing-library/react-native`. | ||
*/ | ||
export const renderWithAtoms = <T, >( | ||
component: React.ReactElement, | ||
options: IRenderWithAtomsOptions<T>, | ||
) => { | ||
const {initialValues} = options; | ||
return render(component, { | ||
wrapper: ({children}: { children: React.JSX.Element }) => ( | ||
<HydrateAtomsWrapper initialValues={initialValues}> | ||
{children} | ||
</HydrateAtomsWrapper> | ||
), | ||
...options, | ||
}); | ||
}; | ||
vanGalilea marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or 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,21 @@ | ||
import * as React from 'react'; | ||
|
||
import { PrimitiveAtom } from 'jotai/vanilla/atom'; | ||
import { useHydrateAtoms } from 'jotai/utils'; | ||
import { RenderOptions as RntlRenderOptions } from '@testing-library/react-native'; | ||
|
||
type WithInitialValue<Value> = { | ||
init: Value; | ||
vanGalilea marked this conversation as resolved.
Show resolved
Hide resolved
|
||
}; | ||
type UseHydrateAtomsParams = Parameters<typeof useHydrateAtoms>; | ||
export type InitialValues = UseHydrateAtomsParams[0]; | ||
vanGalilea marked this conversation as resolved.
Show resolved
Hide resolved
|
||
export type InitialValue<Value> = [PrimitiveAtom<Value> & WithInitialValue<Value>, Value]; | ||
|
||
export interface IRenderWithAtomsOptions<T> extends RntlRenderOptions { | ||
vanGalilea marked this conversation as resolved.
Show resolved
Hide resolved
|
||
initialValues: Array<InitialValue<T>>; | ||
} | ||
|
||
export interface IHydrateAtomsProps<T> { | ||
vanGalilea marked this conversation as resolved.
Show resolved
Hide resolved
|
||
initialValues: Array<InitialValue<T>>; | ||
children: React.JSX.Element; | ||
} |
This file contains hidden or 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
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.
Uh oh!
There was an error while loading. Please reload this page.