forked from shiftkey-labs/SKNotesStarter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
78 lines (72 loc) · 2.65 KB
/
db.js
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
import { createApi, fakeBaseQuery } from '@reduxjs/toolkit/query/react'
import uuid from 'react-native-uuid';
import AsyncStorage from '@react-native-async-storage/async-storage';
export const dbApi = createApi({
reducerPath: 'dbApi',
tagTypes: ['Notes'],
baseQuery: fakeBaseQuery(),
endpoints: (build) => ({
fetchNotes: build.query({
async queryFn() {
const serializedNotes = await AsyncStorage.getItem('notes');
const notes = JSON.parse(serializedNotes);
return { data: [notes] }
},
providesTags: (result) => ['Notes']
}),
searchNotes: build.query({
async queryFn(searchString) {
const serializedNotes = await AsyncStorage.getItem('notes');
const notes = JSON.parse(serializedNotes);
if (searchString == "") {
return { data: notes || [] }
} else {
const filteredNotes = notes.filter(note => {
const { title, content } = note;
const s = searchString.toLowerCase();
return title.toLowerCase().indexOf(s) !== -1 || content.toLowerCase().indexOf(s) !== -1;
});
return { data: filteredNotes || [] }
}
},
providesTags: (result) => ['Notes']
}),
addNote: build.mutation({
async queryFn(note) {
const serializedNotes = await AsyncStorage.getItem('notes');
const notes = JSON.parse(serializedNotes) || [];
note.id = uuid.v4();
notes.unshift(note);
await AsyncStorage.setItem('notes', JSON.stringify(notes));
return { data: note }
},
invalidatesTags: ['Notes'],
}),
deleteNote: build.mutation({
async queryFn(note) {
const serializedNotes = await AsyncStorage.getItem('notes');
let notes = JSON.parse(serializedNotes) || [];
notes = notes.filter(x => x.id !== note.id);
await AsyncStorage.setItem('notes', JSON.stringify(notes));
return { data: note };
},
invalidatesTags: ['Notes'],
}),
updateNote: build.mutation({
async queryFn(note) {
const serializedNotes = await AsyncStorage.getItem('notes');
const notes = JSON.parse(serializedNotes) || [];
const updatedNotes = notes.map((n) => {
if (n.id === note.id) {
return { ...n, title: note.title, content: note.content };
}
return n;
});
await AsyncStorage.setItem('notes', JSON.stringify(updatedNotes));
return { data: note }
},
invalidatesTags: ['Notes'],
}),
}),
})
export const { useFetchNotesQuery, useSearchNotesQuery, useAddNoteMutation, useUpdateNoteMutation, useDeleteNoteMutation } = dbApi