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