ARTICLE AD BOX
I am using React-Query and Axios for data fetching. Whenever a user navigates to a dynamic page and then navigates back with mouse click, for example backward button, it gets error:
Uncaught TypeError: query.data?.map is not a function
I have checked for the output in console.log(query.data) and it is expected to give array, but it gives undefined. I am pretty sure I might be missing something in provided code down below.
console.log(query.data) Expected:
{[ name:'josh', surname: 'green', id:2 ], ... }Result
undefinedI might lack knowledge of React-Query because this is my first time using it in project.
axios
import axios from 'axios' import { apiUrl } from './apiUrl' export const dataFn = axios.create({ baseURL: apiUrl, }) export default async function fetchData() { const res = await dataFn.get('users') if (!res.data) { throw new Error('Data not found') } return res.data }React-Query
export const useFetchData = () => { const { data, isLoading, error } = useQuery<IData[]>({ queryKey: ['data'], queryFn: () => fetchData(), }) return { data, isLoading, error } }Data interface
export interface IData { name: string, surname: string, id: number, }I am getting error here.
const query = useFetchData() return ( <PageLayout > {query.isLoading && <CardSkeleton />} {query?.data && query?.data?.map(({ name,surname,id }, index) => { return ( <Card name={name} surname={surname} id={number} /> ) })} </PageLayout > )Card component is using useNavigate() hook which navigates user to dynamic page where each user is displayed.
I tried to wrap component in try/catch block, this works but I don't think that it is appropriate solution.
