r/learnreactjs • • Jan 13 '24

After I select user and select back to all, it doesn't fetch any posts. How to fix this?

import { useQuery } from "@tanstack/react-query";
import React, { useState } from "react";
import axios from "axios";
import { Select } from "@chakra-ui/react";
interface Posts {
id: number;
title: string;
}
const Posts = () => {
const [userId, setUserId] = useState<number | undefined>(undefined);
const fetchPosts = () => {
return axios
.get<Posts[]>("https://jsonplaceholder.typicode.com/posts", {
params: {
userId,
},
})
.then((res) => res.data);
};
const { data: Posts, error } = useQuery({
queryKey: userId ? ["users", userId, "posts"] : ["posts"],
queryFn: fetchPosts,
// staleTime: 1 * 60 * 1000,
});
if (error) return <div> {error.message}</div>;
return (
<>
<Select
mt={10}
onChange={(e) => setUserId(parseInt(e.target.value))}
value={userId}
>

<option value="">all</option> <option value="1">User 1</option> <option value="2">User 2</option> <option value="3">User 3</option> </Select> <ul>{Posts?.map((post) => <li key={post.id}>{post.title}</li>)}</ul> </> ); }; export default Posts;

2 Upvotes

1 comment sorted by

1

u/purpleliving Jan 14 '24

If you reformat this like a code block it would be a lot easier to read.