Dear All
I use reactquery for updating the data in my code like this:
import { useState } from "react";
import usePosts from "./hooks/usePosts";
const PostList = () => {
const[userId,setUserId]=useState<number>()
const { data: posts, error, isLoading } = usePosts(userId);
if (error) return <p>{error.message}</p>;
if (isLoading) return <p>Is Loading...</p>;
return (
<>
<select className="form-select mb-3" onChange={(event=>{
setUserId(parseInt(event.target.value))
})} value={userId}>
<option value="">All Users</option>
<option value="1">User 1</option>
<option value="2">User 2</option>
<option value="3">User 3</option>
</select>
<ul className="list-group">
{posts?.map((post) => (
<li key={post.id} className="list-group-item">
{post.title}
</li>
))}
</ul>
</>
);
};
export default PostList;
and this is my usePost file:
import { useQuery } from "@tanstack/react-query";
import axios from "axios";
interface Post {
id: number;
title: string;
body: string;
userId: number;
}
interface PostQuery{
userId:number | undefined
}
const usePosts = (query:PostQuery) =>useQuery({
queryKey: ["posts",query],
queryFn: () =>
axios
.get<Post[]>("https://jsonplaceholder.typicode.com/posts",{
params:{
userId:query.userId
}
})
.then((res) => res.data),
});
export default usePosts
and I face this error:
Argument of type ‘number | undefined’ is not assignable to parameter of type ‘PostQuery’.
Type ‘undefined’ is not assignable to type ‘PostQuery’.ts(2345)const userId: number | undefined
View Problem (Alt+F8)
Quick Fix… (Ctrl+.)
why does this error apear? I already note it in my code that the userId could be undefined
Thanks for your help in advance