-
Sorry if this is a silly question, but I can't for the life of me figure out how to fetch items from an API and put them in a list with reactive behaviour. Suppose I want to retrieve all todo items from https://jsonplaceholder.typicode.com/todos endpoint and once they are fetched, put them in an unordered list with each item's title wrapped in I used this code: const App = () => {
const items = van.state([]);
fetch('https://jsonplaceholder.typicode.com/todos')
.then(response => response.json())
.then(data => items.val = data);
return div(
ul(
() => items.val.map(item => li(item.title))
)
);
};
van.add(document.body, App()); But this renders to:
But when I remove the lambda from the return div(
() => ul(items.val.map(item => li(item.title)))
); It then works:
I know it is somewhat related to the spread operator, but I can't figure out how. I read that state changes should affect the smallest possible components, so putting the lambda in Side note: In the official VanJS examples, the counter example does not use a binding function, but the counter still updates: const Counter = () => {
const counter = van.state(0)
return span(
"❤️ ", counter, " ", // not wrapped in () =>
button({onclick: () => ++counter.val}, "👍"),
button({onclick: () => --counter.val}, "👎"),
)
}
van.add(document.body, Counter()) But then I have to use it in my code for reactive behaviour. What gives? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
In VanJS, for state-derived child nodes, the binding function can't return an array of DOM nodes. They have to be encapsulated under a parent node - In the const Counter = () => {
const counter = van.state(0)
return span(
"❤️ ", counter, " ", // not wrapped in () =>
button({onclick: () => ++counter.val}, "👍"),
button({onclick: () => --counter.val}, "👎"),
)
}
van.add(document.body, Counter())
|
Beta Was this translation helpful? Give feedback.
In VanJS, for state-derived child nodes, the binding function can't return an array of DOM nodes. They have to be encapsulated under a parent node -
<ul>
in your case. Sorry for the confusion. This is due to the limit of DOM API.In the
Counter
example:counter
can be considered as a syntax sugar for() => counter.val
.