diff --git a/src/components/create-task/task-form-control.tsx b/src/components/create-task/task-form-control.tsx index 0480568..d4a7e70 100644 --- a/src/components/create-task/task-form-control.tsx +++ b/src/components/create-task/task-form-control.tsx @@ -5,12 +5,45 @@ import { format } from 'date-fns'; import { Task, TaskFields } from '@/types'; import { DATE_FORMAT } from '@/constants'; import { taskFormSchema } from '@/components/task-form/task-form-schema'; -import { createTask } from '@/services/tasks'; +import { createTask, getTasksCollection } from '@/services/tasks'; import { useNavigate } from 'react-router-dom'; +import { onSnapshot, query } from 'firebase/firestore'; +import { useEffect, useRef, useState } from 'react'; export const TaskFormControl = () => { + const isFormSubmitted = useRef(false); + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState(null); const navigate = useNavigate(); + useEffect(() => { + const q = query(getTasksCollection()); + const unsubscribe = onSnapshot( + q, + (snapshot) => { + setIsLoading(true); + setError(null); + + const docChanges = snapshot.docChanges(); + const isTaskCreated = docChanges.length && docChanges[0].type === 'added'; + + if (isTaskCreated && isFormSubmitted.current) { + navigate('/tasks'); + } + + setIsLoading(false); + }, + (error) => { + setError('Failed navigate to tasks page. Please try again later.'); + console.error('Firestore error: ', error); + + setIsLoading(false); + } + ); + + return () => unsubscribe(); + }, [navigate]); + const form = useForm({ resolver: zodResolver(taskFormSchema), defaultValues: { @@ -20,6 +53,8 @@ export const TaskFormControl = () => { }); const handleSubmit = async (values: TaskFields & Pick) => { + isFormSubmitted.current = true; + const formattedValues = { ...values, deadline: format(values.deadline, DATE_FORMAT), @@ -27,12 +62,19 @@ export const TaskFormControl = () => { }; try { - await createTask(formattedValues); - navigate('/tasks'); + createTask(formattedValues); } catch (error) { console.error('Error inserting task to db: ', error); } }; + if (isLoading) { + return
Loading task...
; + } + + if (error) { + return
Error: {error}
; + } + return ; }; diff --git a/src/components/tasks/tasks.tsx b/src/components/tasks/tasks.tsx index 7ebb345..7aac9d7 100644 --- a/src/components/tasks/tasks.tsx +++ b/src/components/tasks/tasks.tsx @@ -13,12 +13,12 @@ export const Tasks = () => { const q = query(getTasksCollection()); const unsubscribe = onSnapshot( q, - (querySnapshot) => { + (snapshot) => { setIsLoading(true); setError(null); try { - const todos = querySnapshot.docs.map((doc) => ({ + const todos = snapshot.docs.map((doc) => ({ ...(doc.data() as Omit), id: doc.id, }));