Converted main page to use react query

This commit is contained in:
keannu125 2023-02-25 21:18:16 +08:00
parent d12d21624f
commit a7b556d0dd

View file

@ -5,30 +5,21 @@ import { useNavigate } from "react-router-dom";
import Note from "../Note/Note";
import { Button } from "@mui/material";
import axios from "axios";
import { useQuery } from "react-query";
export default function Notes() {
const navigate = useNavigate();
const [notes, setNotes] = useState([]);
const [error, setError] = useState(false);
function server_get() {
axios
.get("http://localhost:8000/api/v1/notes/", { timeout: 50 })
.then((res) => {
console.log("Server Response", res.data);
setError(false);
setNotes(res.data);
})
.catch((err) => {
setError(true);
});
}
useEffect(() => {
server_get();
const interval = setInterval(() => {
server_get();
}, 1000);
return () => clearInterval(interval);
}, []);
const {
data: notes,
isLoading,
error,
} = useQuery("notes", () => {
return fetch("http://localhost:8000/api/v1/notes/").then((res) => {
const result = res.json();
console.log();
return result;
});
});
if (error) {
return (
<div style={styles.note}>
@ -36,6 +27,13 @@ export default function Notes() {
</div>
);
}
if (isLoading) {
return (
<div style={styles.note}>
<p style={styles.text_medium}>Loading Notes...</p>
</div>
);
}
if (notes.length === 0) {
return (
<div style={styles.note}>
@ -53,6 +51,7 @@ export default function Notes() {
</div>
);
}
return (
<>
{notes.map(
@ -63,13 +62,13 @@ export default function Notes() {
id: number;
date_created: string;
},
i
index: number
) => {
console.log(note);
return (
<Note
id={note.id}
key={i}
key={index}
title={note.title}
content={note.content}
date_created={note.date_created}