Skip to content

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 4 commits into from
Jul 12, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions examples/cookbook/jotai/TodoList.test.tsx
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]);
});
51 changes: 51 additions & 0 deletions examples/cookbook/jotai/TodoList.tsx
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'}>
{item.text}
</Text>
)}
/>
<Pressable accessibilityRole="button" onPress={handleAddTodo}>
<Text>Add a random to-do</Text>
</Pressable>
</View>
);
}

// Available for use outside react components
export const store = createStore();
export const getTodos = (): TodoItem[] => store.get(todosAtom);
export const addTodo = (newTodo: TodoItem) => {
const todos = getTodos();
store.set(todosAtom, [...todos, newTodo]);
};
35 changes: 35 additions & 0 deletions examples/cookbook/jotai/test-utils.tsx
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,
});
};
21 changes: 21 additions & 0 deletions examples/cookbook/jotai/types.ts
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;
};
type UseHydrateAtomsParams = Parameters<typeof useHydrateAtoms>;
export type InitialValues = UseHydrateAtomsParams[0];
export type InitialValue<Value> = [PrimitiveAtom<Value> & WithInitialValue<Value>, Value];

export interface IRenderWithAtomsOptions<T> extends RntlRenderOptions {
initialValues: Array<InitialValue<T>>;
}

export interface IHydrateAtomsProps<T> {
initialValues: Array<InitialValue<T>>;
children: React.JSX.Element;
}
1 change: 1 addition & 0 deletions examples/cookbook/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"dependencies": {
"expo": "^50.0.4",
"expo-status-bar": "~1.11.1",
"jotai": "^2.8.4",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-native": "0.73.2",
Expand Down
Loading
Loading