Skip to main content

Create state

In this part you'll learn how to create stocked state in your components

Initial state

Let's provide initial state for the stock root component

./src/App.jsx
import { StockRoot } from 'stocked';

function App() {
return (
<StockRoot
initialValues={{
todos: [
{
title: 'Display todos',
completed: false,
},
{
title: 'Add the ability to mark completed todos',
completed: false,
},
{
title: 'Add possibility to create new todo',
completed: false,
},
{
title: 'Filter todos',
completed: false,
},
{
title: 'Optimize',
completed: false,
},
],
}}
>
<h1>Todo list!</h1>
</StockRoot>
);
}

export default App;

Display todos

Now, we'll create a component - TodoList.jsx. This component will render list of todo items.

./src/TodoList.jsx
import { useStockValue } from 'stocked';
export const TodoList = () => {
const todos = useStockValue('todos');

return (
<ul>
{todos.map(({ title }, key) => (
<li key={key}>{title}</li>
))}
</ul>
);
};

As you can see, we're using array of todos from the stock. Every time when todos will be updated in the stock, our TodoList component will re-render. Let's use this component in our app:

./src/App.jsx
import { TodoList } from './TodoList';

// ...

function App() {
return (
<StockRoot
initialValues={{ /* ... */ }}
>
<h1>Todo list!</h1>
<TodoList />
</StockRoot>
);
}

export default App;

Intermediate result

And this is what we have at the moment:

Result

Let's move on.