I've been trying to GET
data from the JSON-server using @tanstack/react-query
in the same code pattern that worked for me in another project. However, this time the function seems to have not been called for some reason, causing the data to return 'undefined'. What am I missing here?
Here is the code in the component task-list.tsx
:
import { fetchAllTasks } from "../../api/tasks-api"
import TaskItem from "./task-item/task-item"
import style from './task-list.module.scss'
const TaskList = () => {
// This supposed to work, but isn't!
const { data: tasks, isLoading } = fetchAllTasks()
// This logs: undefined
console.log('tasklists - fetchAllTasks:', tasks)
return (
<div className={`${style['TaskList']}`}>
<ul>
{
!isLoading && tasks && tasks?.length < 1 ?
<p className={`${style['no-task']}`}>
+++ Task List is Empty +++
</p>
:
tasks?.map((task) =>
<TaskItem
key={task.toString()}
atom={task}
/>
)
}
</ul>
</div>
)
}
export default TaskList
Here is the fetchAllTasks()
function in task-api.ts
:
import { useQuery } from "@tanstack/react-query"
import axios from "axios"
import { Task } from "../types"
export const fetchAllTasks = () => {
return useQuery({
queryKey: ['tasks'],
queryFn: async () => {
const response = await axios.get('http://localhost:3100/tasks')
const data: unknown = await response.data()
// This doesn't appear in the console log at all
console.log('data: ', data)
return data as Task[]
}
})
}
Here is what shows up in the browser:
Here is the response from the backend:
Here is how the network tab of the browser looks like after a page refresh.
The link to the project repo: https://github.com/iceyisaak/todoapp/tree/tanstack-query/src
Help is very much appreciated :)
Axios returns data as property, so you do not invoke data as method on the response object and because it is a property you do not need to use await.
const response = await axios.get('http://localhost:3100/tasks')
const data: unknown = response.data