How to use fetched data as State?

I am getting data (a post) from trpc inside my component:
[id].tsx
const Post = (
props: InferGetServerSidePropsType<typeof getServerSideProps>
) => {
const { id } = props;
const postData = trpc.post.getPost.useQuery({
postId: id,
});

...
[id].tsx
const Post = (
props: InferGetServerSidePropsType<typeof getServerSideProps>
) => {
const { id } = props;
const postData = trpc.post.getPost.useQuery({
postId: id,
});

...
The user should be able to edit the post, so I want to make the fetched data a state via useState. I tried:
useEffect(() => {
setPostState({
title: post.data.title,
description: post.data.description,
});
}, []);
useEffect(() => {
setPostState({
title: post.data.title,
description: post.data.description,
});
}, []);
but it doesnt work. I need to set the State after the data finished loading. How?
12 Replies
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Johnson
JohnsonOP3y ago
I thought in order for a user to modify the post (and then eventually re-write that modification to the database), it would make sense to manage a state. This way, the user can modify whatever attribute of the state that he wants, and in the end, I just take that state and write to db I don't think postData can be regarded as a state. I can't do something like setPostData(), right?
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Johnson
JohnsonOP3y ago
ye that makes sense
cje
cje3y ago
React Query and Forms
Forms tend to blur the line between server and client state, so let's see how that plays together with React Query.
Johnson
JohnsonOP3y ago
but when they are edited, where to save the changes to? I can only think of useState
cje
cje3y ago
this article gives you a couple of different options
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Johnson
JohnsonOP3y ago
ye just imagine that the only thing that changes when you edit the post is that the input field it's in, becomes editable so I guess preview, yeah
Johnson
JohnsonOP3y ago
using the simple approach (https://tkdodo.eu/blog/react-query-and-forms#the-simple-approach), do I have to use the useMutation hook? because right now I get an error Argument of type 'void' is not assignable to parameter of type 'SubmitHandler<FieldValues>'.ts(2345) while doing this:
React Query and Forms
Forms tend to blur the line between server and client state, so let's see how that plays together with React Query.
Johnson
JohnsonOP3y ago
<form
onSubmit={handleSubmit( postMutation.mutate({ post: postData.data })
)}
>
<form
onSubmit={handleSubmit( postMutation.mutate({ post: postData.data })
)}
>
Johnson
JohnsonOP3y ago
nevermind, me stupid
Want results from more Discord servers?
Add your server