@@ -6,6 +6,8 @@ import { useMutation, useQueryClient } from 'react-query'
66import toast , { Toaster } from 'react-hot-toast'
77import { useRef , useState } from 'react'
88import { Markdown , A } from '@/components'
9+ import { HomePageFeedUpdateType } from 'src/pages'
10+ import { GoalResponse } from 'src/pages/[username]'
911
1012type Inputs = {
1113 description : string
@@ -41,15 +43,78 @@ export default function NewUpdate({
4143 return res . json ( )
4244 } ) ,
4345 {
44- onSuccess : ( ) => {
46+ onSuccess : ( data , variables , context ) => {
4547 toast . success ( 'You have successfully added an update.' , {
4648 id : toastId . current ,
4749 } )
48- queryClient . refetchQueries ( '/api/fauna/goals/all-goals-by-user' )
50+
51+ queryClient . setQueryData < GoalResponse [ ] > (
52+ '/api/fauna/goals/all-goals-by-user' ,
53+ ( oldData ) => {
54+ if ( ! oldData ) {
55+ return oldData
56+ }
57+ return oldData . map ( ( goalResponse ) => {
58+ if ( goalResponse . id === goal . id ) {
59+ goalResponse . updates = {
60+ data : [
61+ ...goalResponse . updates . data ,
62+ {
63+ id : data . response . id ,
64+ description : data . response . description ,
65+ createdAt : data . response . createdAt ,
66+ postedBy : data . response . postedBy ,
67+ } ,
68+ ] ,
69+ }
70+ }
71+ return goalResponse
72+ } )
73+ }
74+ )
75+
4976 if ( updateFromHomePage ) {
50- queryClient . refetchQueries ( '/api/fauna/all-updates' )
51- queryClient . refetchQueries ( [ '/api/fauna/recent-updates' , goal . id ] )
77+ queryClient . setQueryData < { updates : HomePageFeedUpdateType [ ] } > (
78+ '/api/fauna/all-updates' ,
79+ ( oldData ) => {
80+ if ( ! oldData ) {
81+ return oldData
82+ }
83+ return {
84+ updates : [ data . response , ...oldData . updates ] ,
85+ }
86+ }
87+ )
88+
89+ queryClient . setQueryData < { response : GoalResponse } > (
90+ [ '/api/fauna/recent-updates' , goal . id ] ,
91+ ( oldData ) => {
92+ // If the recent-updates panel is not opened yet
93+ // then this oldData will be undefined
94+ // since the corresponsing query is not execcuted even once
95+ if ( ! oldData ) {
96+ return oldData
97+ }
98+ return {
99+ response : {
100+ ...oldData . response ,
101+ updates : {
102+ data : [
103+ ...oldData . response . updates . data ,
104+ {
105+ id : data . response . id ,
106+ description : data . response . description ,
107+ createdAt : data . response . createdAt ,
108+ postedBy : data . response . postedBy ,
109+ } ,
110+ ] ,
111+ } ,
112+ } ,
113+ }
114+ }
115+ )
52116 }
117+
53118 reset ( )
54119 } ,
55120 onError : ( ) => {
0 commit comments