Making Requests
In this section we'll move back into our NotesPage
and change our data source from fakeData.js
, to the data we have in our Appwrite backend.
Render notes
Comment out fakeNotes
import and import the db
object.
// import { fakeData as notes } from "../assets/fakeData.js";
import { db } from "../appwrite/databases";
We'll use the init
method to make a request to our Appwrite backend by calling db.notes.list()
, and then update our notes
state with the response data.
const NotesPage = () => {
const [notes, setNotes] = useState([]);
useEffect(() => {
init();
}, []);
const init = async () => {
const response = await db.notes.list();
setNotes(response.documents);
};
Add body parser
Because our note body
attribute holds stringified JSON data, we call the JSON.parse
method on our body. In some cases, we may hold plain text in this field which is not stringified, therefor causing an error when we call JSON.parse
.
To avoid this error, we'll create a function that attempts to parse our note body data, and if this data is not valid JSON data, we will return the plain string value, therefore avoiding any errors.
Create the bodyParser
method in utils.js
export const bodyParser = (value) => {
try {
JSON.parse(value);
return JSON.parse(value);
} catch (error) {
return value;
}
}
Now we can update the body value inside of NoteCard.jsx
import { setNewOffset, autoGrow, setZIndex, bodyParser } from "../utils";
//..
const NoteCard = ({ note }) => {
let position = JSON.parse(note.position);
const colors = JSON.parse(note.colors);
const body = bodyParser(note.body);