How to type object like this as props

Heyy I play a little with trpc and optimistic updates and I wonder how can I type object like this when I pass it as props.
const addTodo = api.todos.createTodo.useMutation({
async onMutate(newTodo) {
// Cancel outgoing fetches (so they don't overwrite our optimistic update)
await utils.todos.getAllTodos.cancel();

// Get the data from the queryCache
const prevData = utils.todos.getAllTodos.getData();

// Optimistically update the data with our new post
utils.todos.getAllTodos.setData(
undefined,
(old) => [...(old as Todo[]), newTodo] as Todo[]
);

// Return the previous data so we can revert if something goes wrong
return { prevData };
},
onError(err, newPost, ctx) {
// If the mutation fails, use the context-value from onMutate
utils.todos.getAllTodos.setData(undefined, ctx?.prevData);
},
onSettled() {
// Sync with server once mutation has settled
void utils.todos.getAllTodos.invalidate();
},
});
const addTodo = api.todos.createTodo.useMutation({
async onMutate(newTodo) {
// Cancel outgoing fetches (so they don't overwrite our optimistic update)
await utils.todos.getAllTodos.cancel();

// Get the data from the queryCache
const prevData = utils.todos.getAllTodos.getData();

// Optimistically update the data with our new post
utils.todos.getAllTodos.setData(
undefined,
(old) => [...(old as Todo[]), newTodo] as Todo[]
);

// Return the previous data so we can revert if something goes wrong
return { prevData };
},
onError(err, newPost, ctx) {
// If the mutation fails, use the context-value from onMutate
utils.todos.getAllTodos.setData(undefined, ctx?.prevData);
},
onSettled() {
// Sync with server once mutation has settled
void utils.todos.getAllTodos.invalidate();
},
});
then
const CreateTodo = ({ addTodo }: ???) => {}
const CreateTodo = ({ addTodo }: ???) => {}
4 Replies
erik.gh
erik.gh2y ago
what do you want to achieve by putting that mutation inside an object bc it's a bit unusual and the type of addTodo is huge
noctate
noctateOP2y ago
https://create.t3.gg/en/usage/trpc/#optimistic-updates i just copied example from the docs to use optimistic updates. I wanted to pass it as props because too different components use this add todo, so didnt wanted repeat myself. For now I choosed to extract all logic inside useTodos hook and just use it something like this:
const CreateTodo = () => {
const {addTodo} = useTodos();
}
const CreateTodo = () => {
const {addTodo} = useTodos();
}
Create T3 App
tRPC 🚀 Create T3 App
The best way to start a full-stack, typesafe Next.js app.
erik.gh
erik.gh2y ago
i think you're on the right track
benten
benten2y ago
I think the hook idea is much better than passing it as props
Want results from more Discord servers?
Add your server