React Course/ UseQuery

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

Did you try to make the userId in the interface optional?

interface PostQuery {
    userId?: number | undefined
}

I can’t test it myself since I haven’t installed react, reactquery etc. but try to make it optional.

Edit: Why aren’t you destructuring the PostQuery object in the usePosts hook? instead of (query: PostQuery) do ({ userId }: PostQuery) so you won’t need to constantly put in query.userId everytime you need to.