https://github.com/rof1yev/tanstack_react_query
@tanstack/react-query - React Query Tutorial
https://github.com/rof1yev/tanstack_react_query
Last synced: 3 months ago
JSON representation
@tanstack/react-query - React Query Tutorial
- Host: GitHub
- URL: https://github.com/rof1yev/tanstack_react_query
- Owner: rof1yev
- Created: 2023-12-03T11:34:08.000Z (about 2 years ago)
- Default Branch: master
- Last Pushed: 2024-07-01T10:59:20.000Z (over 1 year ago)
- Last Synced: 2025-02-23T13:40:17.295Z (10 months ago)
- Language: TypeScript
- Size: 50.8 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Fetch data with jsonplaceholder with tanstack-react-query
This project demonstrates how to use `tanstack-react-query` to fetch users and posts from the [jsonplaceholder](https://jsonplaceholder.typicode.com/) API.
## Requirements
- Node.js v12 or higher
- NPM or Yarn
## Installation
1. Clone the repository:
```bash
git clone https://github.com/Rofiyev/tanstack_react_query.git
cd tanstack_react_query
```
2. Install the dependencies:
```bash
npm install
# or
yarn install
```
## Usage
To start the project, run the following command:
```bash
npm start
# or
yarn start
```
## Project Structure
Briefly describe the structure of your project, for example:
- `src/`
- `api/`
- `index.tsx`
- `assets/`
- `react.svg`
- `components/`
- `Navbar.tsx`
- `Posts.tsx`
- `User.tsx`
- `index.ts`
- `interface`
- `index.ts`
- `pages/`
- `Create.tsx`
- `Home.tsx`
- `PostDetail.tsx`
- `index.ts`
- `App.tsx`
- `index.css`
- `main.tsx`
- `vite-env.d.ts`
## Fetching Data with React Query
In `src/api/index.ts`:
```typescript
import axios from "axios";
import { IResPostData, IResUserData } from "../interface";
export async function getUsers() {
const { data } = await axios.get(
"https://jsonplaceholder.typicode.com/users"
);
return data;
}
export async function getUser(id: number) {
const { data } = await axios.get(
`https://jsonplaceholder.typicode.com/users/${id}`
);
return data;
}
export async function getPosts() {
const { data } = await axios.get(
"https://jsonplaceholder.typicode.com/posts"
);
return data;
}
export async function getPost(id: number) {
const { data } = await axios.get(
`https://jsonplaceholder.typicode.com/posts/${id}`
);
return data;
}
export async function createPost({
title,
body,
}: {
title: string;
body: string;
}) {
const { data } = await axios.post(
`https://jsonplaceholder.typicode.com/posts`,
{
title,
body,
userId: 1,
id: Date.now(),
}
);
return data;
}
```
## Components
In `src/component/Navbar.tsx`:
```typescript
import { Link } from "react-router-dom";
export default function Navbar() {
return (
Home
Create
);
}
```
## Interface
In `src/interface/index.ts`:
```typescript
export interface IResUserData {
address: {
city: string;
geo: { lat: string; lng: string };
street: string;
suite: string;
zipcode: string;
};
company: {
bs: string;
catchPhrase: string;
name: string;
};
email: string;
id: number;
name: string;
phone: string;
username: string;
website: string;
}
export interface IResPostData {
body: string;
id: number;
title: string;
userId: number;
}
```
## Pages
In `src/pages/Create.tsx`:
```typescript
import { Navbar } from "../components";
import { useRef, FormEvent } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { createPost } from "../api";
import { useNavigate } from "react-router-dom";
export default function CreatePost() {
const navigate = useNavigate();
const ref = useRef(null);
const queryClient = useQueryClient();
const { status, error, mutate } = useMutation({
mutationFn: createPost,
onSuccess: (newPost) => {
queryClient.setQueryData(["posts", newPost.id], newPost);
navigate(`/posts/${newPost.id}`);
},
});
const handleSubmit = (e: FormEvent) => {
e.preventDefault();
const current = ref.current as HTMLFormElement;
const { title, body } = current;
console.log(title.valueOf());
mutate({
title: title!.value,
body: body!.value,
});
current.reset();
};
console.log(error, status);
return (
Create Post
Sign in
© 2023-2024
);
}
```
In `src/pages/Home.tsx`:
```typescript
import { useQuery } from "@tanstack/react-query";
import { getPosts } from "../api";
import { Navbar, Posts } from "../components";
import { Spinner } from "react-bootstrap";
import { IResPostData } from "../interface";
export default function Home() {
const {
data: posts,
error,
isLoading,
} = useQuery({
queryKey: ["postsData"],
queryFn: getPosts,
});
if (isLoading)
return (
Loading...
);
if (error) return
An error occurred: {error.message};
return (
<>
{posts?.map((item: IResPostData) => (
))}
>
);
}
```
In `src/pages/PostDetail.tsx`:
```typescript
import { useParams } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { getPost, getUser } from "../api";
import { Spinner } from "react-bootstrap";
import { Navbar } from "../components";
export default function PostDetail() {
const { id } = useParams();
const {
status: statusPost,
error: errorPost,
data: post,
isLoading: postIsLoading,
} = useQuery({
queryKey: ["postsData", parseInt(id!)],
queryFn: () => getPost(+id!),
});
console.log(errorPost);
const {
status: statusUser,
error: errorUser,
data: user,
isLoading: userIsLoading,
} = useQuery({
enabled: post?.userId != null,
queryKey: ["users", post?.userId],
queryFn: () => getUser(post!.userId!),
});
console.log(errorUser);
console.log(user);
if (postIsLoading) {
return (
Post Loading...
);
}
if (userIsLoading) {
return (
User Loading...
);
}
return (
{statusPost === "success" && (
<>
Post title
{post.title.charAt(0).toUpperCase() + post.title.slice(1)}
{post.body.charAt(0).toUpperCase() + post.title.slice(1)}
>
)}
{statusUser === "success" && (
Fullname: {user.name}
Phone number: {user.phone}
Email: {user.email}
)}
);
}
```
In `src/App.tsx`:
```typescript
import { Routes, Route } from "react-router-dom";
import { Home, PostDetail, CreatePost } from "./pages";
export default function App() {
return (
} />
} />
} />
);
}
```
In `src/main.tsx`:
Here we need to wrap our main component using the `tanstack-react-query provider`! And it is very important that we give it `query-client` as the provider value!
```typescript
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App.tsx";
import "./index.css";
import { QueryClientProvider, QueryClient } from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import { BrowserRouter } from "react-router-dom";
import "bootstrap/dist/css/bootstrap.min.css";
const queryClient = new QueryClient();
ReactDOM.createRoot(document.getElementById("root")!).render(
);
```