'React custom hook different parameter type

So in my project I have several instances where I have to fetch data from firebase that would change rather frequently. I have decided to use custom hooks to fetch the data and reuse them in different components if need be.

For example, I might need to retrieve the data for a single task and other times I need to fetch data for an array of tasks.

Currently I have implemented the following to retrieve a single task:

const useTask = (taskId: string) => {
  const [taskData, setTaskData] = useState<TaskWithId>({} as TaskWithId)

  useEffect(() => {
    const taskCollectionRef = collection(db, 'tasks')
    const qTask = query(taskCollectionRef, where(documentId(), '==', taskId))
    const unsubscribe = onSnapshot(qTask, querySnapshot => {
      querySnapshot.forEach(doc => {
        setTaskData({
          id: doc.id,
          title: doc.data().title,
          createdBy: doc.data().createdBy,
          description: doc.data().description,
          assignedTo: doc.data().assignedTo,
          parent: doc.data().parent,
          createdAt: doc.data().createdAt,
          modifiedAt: doc.data().modifiedAt,
          dueDate: doc.data().dueDate,
          completed: doc.data().completed,
        })
      })
    })
    return unsubscribe
  }, [taskId])
  return taskData
}

export default useTask

For multiple tasks, I am using another custom hook as follows:

const useTaskArr = (taskArr: string[]) => {
  const [taskArrData, setTaskArrData] = useState<TaskWithId[]>([])

  useEffect(() => {
    if (taskArr.length == 0) {
      setTaskArrData([])
      return
    }
    const taskCollectionRef = collection(db, 'tasks')
    const qTask = query(taskCollectionRef, where(documentId(), 'in', taskArr))
    const unsubscribe = onSnapshot(qTask, querySnapshot => {
      setTaskArrData(
        querySnapshot.docs.map<TaskWithId>(doc => ({
          id: doc.id,
          title: doc.data().title,
          createdBy: doc.data().createdBy,
          description: doc.data().description,
          assignedTo: doc.data().assignedTo,
          parent: doc.data().parent,
          createdAt: doc.data().createdAt,
          modifiedAt: doc.data().modifiedAt,
          dueDate: doc.data().dueDate,
          completed: doc.data().completed,
        }))
      )
    })
    return unsubscribe
  }, [taskArr])
  return taskArrData
}

export default useTaskArr

As you can see, the query is different if it is a single task or an array and the type of the state is also different.

How could I merge both in a single custom hook and pass whether I would need to retrieve an array of tasks or a single one?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source