Deriving state from fetched data #661
Unanswered
theodoretliu
asked this question in
General
Replies: 1 comment 2 replies
-
|
You can put this inside a useEffect(() => {
// this will run on every render which seems wrong
for (let todo of data.todos) {
// append a todo to the local state along with "check"
setTodos([...todos, { checked: false, ...todo }]);
}
}, [data])Although I don't think you should maintain your local state. SWR is your state. I'd implement it this way: function TodoList() {
const { data, mutate } = useSWR("/getTodos", fetcher);
if (data === undefined) {
return <div>Loading</div>;
}
const todos = data.todos;
return (
<div>
{todos.map((todo, index) => (
<div
onClick={() => {
const updatedTodo = {...todo, checked: !todo.checked};
const updatedTodos = [...todos];
updatedTodos[index] = updatedTodo;
mutate(updatedTodos, false);
}}
>
{todo.checked && "I'm checked"}
</div>
))}
</div>
);
} |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hi! I was wondering what the best practices were for augmenting the data returned from
useSWRwith state. As a toy example, suppose I useuseSWRto fetch a user's todos from an API endpoint. But on the client, the user should be able to "check" those todos to mark them for exporting to CSV or similar. The "check" operation should be stored as client state and ideally would "augment" the fetched data in a way. Is there a proper way to do this? As an incomplete example, see belowBeta Was this translation helpful? Give feedback.
All reactions