-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathnoteSlice.js
65 lines (59 loc) · 2.06 KB
/
noteSlice.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
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import noteService from './noteService'
// NOTE: use a extractErrorMessage function to save some repetition
import { extractErrorMessage } from '../../utils'
// NOTE: removed isLoading, isSuccess, isError, message and reset
// loading can be infered from presence or absence of notes
// success can be infered from presence or absence of notes
// error meassages can be recieved at component level from our AsyncThunkAction
// reset was never actually used
const initialState = {
notes: null,
}
// Get ticket notes
export const getNotes = createAsyncThunk(
'notes/getAll',
async (ticketId, thunkAPI) => {
try {
const token = thunkAPI.getState().auth.user.token
return await noteService.getNotes(ticketId, token)
} catch (error) {
return thunkAPI.rejectWithValue(extractErrorMessage(error))
}
}
)
// Create ticket note
export const createNote = createAsyncThunk(
'notes/create',
async ({ noteText, ticketId }, thunkAPI) => {
try {
const token = thunkAPI.getState().auth.user.token
return await noteService.createNote(noteText, ticketId, token)
} catch (error) {
return thunkAPI.rejectWithValue(extractErrorMessage(error))
}
}
)
export const noteSlice = createSlice({
name: 'note',
initialState,
extraReducers: (builder) => {
builder
.addCase(getNotes.pending, (state) => {
// NOTE: reset notes to null on pending so we can show a Spinner while
// fetching notes
state.notes = null
})
.addCase(getNotes.fulfilled, (state, action) => {
// NOTE: even if there are no notes for the ticket we get an empty
// array, so we can use this to detect if we have notes or are fetching
// notes. Payload will be an array of notes or an empty array, either
// means we have finished fetching the notes.
state.notes = action.payload
})
.addCase(createNote.fulfilled, (state, action) => {
state.notes.push(action.payload)
})
},
})
export default noteSlice.reducer