-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNoteState.js
More file actions
96 lines (81 loc) · 3.13 KB
/
NoteState.js
File metadata and controls
96 lines (81 loc) · 3.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import React, { useState } from "react";
import NoteContext from "./noteContext";
const NoteState = (props) => {
const host = "http://localhost:5000"
const notesInitial = []
const [notes, setNotes] = useState(notesInitial)
//Get all notes
const getNotes = async () => {
//API call
const response = await fetch(`${host}/api/notes/fetchallnotes`, {
method: 'GET', // *GET, POST, PUT, DELETE, etc.
headers: {
'Content-Type': 'application/json',
'auth-token': localStorage.getItem('auth-token')
}
});
const json = await response.json()
setNotes(json)
}
//Add note
const addNote = async (title, description, tag) => {
//API call
const response = await fetch(`${host}/api/notes/addnote`, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
headers: {
'Content-Type': 'application/json',
'auth-token': localStorage.getItem('auth-token')
},
body: JSON.stringify({ title, description, tag }) // body data type must match "Content-Type" header
});
const note = await response.json()
setNotes(notes.concat(note))
}
//Delete a note
const deleteNote = async (id) => {
//API call
const response = await fetch(`${host}/api/notes/deletenote/${id}`, {
method: 'DELETE', // *GET, POST, PUT, DELETE, etc.
headers: {
'Content-Type': 'application/json',
'auth-token': localStorage.getItem('auth-token')
},
});
const json = await response.json(); // parses JSON response into native JavaScript objects
console.log(json)
const newNotes = notes.filter((note) => { return note._id !== id })
setNotes(newNotes)
}
//Edit a note
const editNote = async (id, title, description, tag) => {
//API call
const response = await fetch(`${host}/api/notes/updatenote/${id}`, {
method: 'PUT', // *GET, POST, PUT, DELETE, etc.
headers: {
'Content-Type': 'application/json',
'auth-token': localStorage.getItem('auth-token')
},
body: JSON.stringify({ title, description, tag }) // body data type must match "Content-Type" header
});
const json = await response.json(); // parses JSON response into native JavaScript objects
console.log(json)
let newNotes = JSON.parse(JSON.stringify(notes))
//logic to edit in client
for (let index = 0; index < newNotes.length; index++) {
const element = newNotes[index];
if (element._id === id) {
newNotes[index].title = title
newNotes[index].description = description
newNotes[index].tag = tag
break
}
}
setNotes(newNotes)
}
return (
<NoteContext.Provider value={{ notes, addNote, deleteNote, editNote, getNotes }}>
{props.children}
</NoteContext.Provider>
)
}
export default NoteState