Reputation: 117
I am trying to learn react-query and been following quite a few guides. However everytime I try with parameters something goes wrong. This code that I have under just keep telling me that Cannot read properties of undefined (reading 'id') even though the console.log(id) prints out the correct number.
const PracticeList = ({id}) => {
const idTest = id
conosole.log(idTest) //this prints 190 and is not undefined
const { isLoading, isFetching, data, isError } = useQuery(["list",{id:idTest}],GetList,{
retry:1,
retryDelay:500
})
if (isLoading) {
return <p>Loading</p>
}
if (isError) {
return <p>Error getting posts...</p>
}
return (
<div> {isFetching && <p>Updating</p>}{data &&<p>{data.lists}</p>}</div>
)
}
export const GetList = async(key,obj)=>{
console.log(key,obj) //This prints that key is defined but obj is undefined?
const {data} = await ShoppingListAPI.get(`/getShoppingList`,{id:obj.id});
return data;
}
This never really happends as it crashes before, but I do know it works from postman.
import axios from 'axios';
export default axios.create({
baseURL:"http://localhost:3005/api/v1/",
});
This is where I set the Id btw.
import './App.css';
import {Container, Typography} from '@mui/material'
import AllLists from './AllLists';
import { useState } from 'react';
import ShoppingList2 from './ShoppingList2';
import Practice from './Practice';
import PracticeList from './PracticeList';
function App() {
const [activeList, setActiveList]= useState(190)
return (
<div className="App">
<Typography>Shopping list</Typography>
<Container maxWidth="lg">
<Practice/>
{activeList&&<PracticeList id={activeList}/>}
</Container>
</div>
);
}
export default App;
Upvotes: 2
Views: 4876
Reputation: 28978
since v3, react-query injects an object called the QueryFunctionContext
into the queryFn. It contains the queryKey, among other information.
So if your query is:
useQuery(["list",{id:idTest}],GetList)
you can extract the queryKey in GetList
via:
const GetList = (queryFunctionContext) => {
const queryKey = queryFunctionContext.queryKey
}
queryKey[0]
will then be "list"
and queryKey[1]
should be your object that contains the id
.
Upvotes: 3
Reputation: 7985
try this
()=>GetList(idTest)
const { isLoading, isFetching, data, isError } = useQuery(["list",{id:idTest}],()=>GetList(idTest),{
Upvotes: 0