skip to Main Content

I’m trying to access the props from this taskList array that I’m grabbing from firestore,
The taskList is an array of objects so shouldn’t I just be able to access them with task.propName?

function App() {
  const [taskList, setTaskList] = useState<Array<object>>()

  const taskCollectionRef = collection(db, "tasks")

  useEffect(() => {
    const getTaskList = async () => {
      // Get data from db
      try {
        const data = await getDocs(taskCollectionRef);
        const filteredData = data.docs.map((doc) => ({ ...doc.data(), id: doc.id, }));
        setTaskList(filteredData);
        console.log(taskList);
      } catch (err) {
        console.error(err);
      }
    }
    getTaskList();
  }, [])

  return (
    <>
      <TopNavbar title={siteTitle} />
      <div>
        {taskList?.map((task) => (
          <div>
            <h1>{task.title}</h1> /* Property 'title' does not exist on type 'object'. */ 
          </div>
        ))}
      </div>
      <Auth />
    </>
  )
}

export default App

I’ve tried changing the type in the useState function but I don’t know what else it could be other than an array of objects.

2

Answers


  1. You can cast the object in map:

    function App() {
      const [taskList, setTaskList] = useState<Array<object>>()
    
      const taskCollectionRef = collection(db, "tasks")
    
      useEffect(() => {
        const getTaskList = async () => {
          // Get data from db
          try {
            const data = await getDocs(taskCollectionRef);
            const filteredData = data.docs.map((doc) => ({ ...doc.data(), id: doc.id, } as YOUR_OBJECT_TYPE));
            setTaskList(filteredData);
            console.log(taskList);
          } catch (err) {
            console.error(err);
          }
        }
        getTaskList();
      }, [])
    
      return (
        <>
          <TopNavbar title={siteTitle} />
          <div>
            {taskList?.map((task) => (
              <div>
                <h1>{task.title}</h1> /* Property 'title' does not exist on type 'object'. */ 
              </div>
            ))}
          </div>
          <Auth />
        </>
      )
    }
    
    Login or Signup to reply.
  2. If you add the fields coming from the API as a type you can solve it like this:

    type Task = {
      title: string
      complete: boolean
      tags: string[]
      }
    const [taskList, setTaskList] = useState<Array<Task>>()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search