Skip to content

Instantly share code, notes, and snippets.

@Zeko369
Created December 30, 2024 16:48
Show Gist options
  • Save Zeko369/932f7c58e215e1366661e2f098d079f7 to your computer and use it in GitHub Desktop.
Save Zeko369/932f7c58e215e1366661e2f098d079f7 to your computer and use it in GitHub Desktop.
"use client";
import { useQuery } from "@tanstack/react-query";
import { useEffect, useState } from "react";
const apiCall = (url: string, options: RequestInit) => {
return fetch(url, {
...options,
headers: {
...options.headers,
...(localStorage.getItem("token")
? { Authorization: `Bearer ${localStorage.getItem("token")}` }
: {}),
},
}).then((res) => res.json());
};
const Login = () => {
const [email, setEmail] = useState("[email protected]");
const [password, setPassword] = useState("asd");
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const formData = new FormData();
formData.append("user[email]", email);
formData.append("user[password]", password);
fetch(`${process.env.NEXT_PUBLIC_API_URL}/auth`, {
method: "POST",
body: formData,
})
.then((res) => res.json())
.then((data) => {
localStorage.setItem("token", data.token);
});
};
return (
<form onSubmit={handleSubmit}>
<input
className="text-black"
type="text"
placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<input
className="text-black"
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button type="submit">Login</button>
</form>
);
};
const Posts = () => {
const posts = useQuery({
queryKey: ["posts"],
queryFn: () => apiCall(`${process.env.NEXT_PUBLIC_API_URL}/posts`, {}),
});
if (posts.isLoading) {
return <h1>Loading...</h1>;
}
if (posts.error) {
return <h1>Error: {posts.error.message}</h1>;
}
const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const formData = new FormData(e.target as HTMLFormElement);
const res = await apiCall(`${process.env.NEXT_PUBLIC_API_URL}/posts`, {
method: "POST",
body: formData,
});
posts.refetch();
};
return (
<div>
<button onClick={() => posts.refetch()}>Refetch</button>
<form className="flex flex-col gap-2" onSubmit={onSubmit}>
<input
name="post[title]"
type="text"
placeholder="Title"
className="text-black"
/>
<input
name="post[content]"
type="text"
placeholder="Content"
className="text-black"
/>
<input
name="post[images][]"
type="file"
multiple
className="text-black"
/>
<button type="submit">Add Post</button>
</form>
{posts.data.map((post: any) => (
<div key={post.id}>
{post.title}
{post.images.map((image: any) => (
<img
key={image.id}
src={image.url.replace("example.com", "foody-backend.zeko.run")}
alt={post.title}
/>
))}
</div>
))}
</div>
);
};
export default function Testing() {
const [token, setToken] = useState(() => localStorage.getItem("token"));
if (!token) {
return <Login />;
}
return <Posts />;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment