-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtopicsSlice.js
50 lines (47 loc) · 1.83 KB
/
topicsSlice.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
import { createSlice } from "@reduxjs/toolkit";
// import another slices reducer to interact with this slices state when called
import { addQuiz } from "../quizzes/quizzesSlice";
export const topicsSlice = createSlice({
name: 'topics',
initialState: {
topics: {
// '123456': {
// id: '123456',
// name: 'name of topic',
// icon: 'icon url',
// quizIds: []
// }
}
},
reducers: {
addTopic: (state, action) => {
state.topics[action.payload.id] = {
id: action.payload.id,
name: action.payload.name,
icon: action.payload.icon,
quizIds: []
}
}
},
extraReducers: (builder) => {
builder
.addCase(addQuiz, (state, action) => {
// if topic doesen't exist early return
if (state.topics[action.payload.topicId] === undefined) {
console.log(action.payload.topicId, 'no topic selected, no topic quizIds array updated');
return;
}
// add quiz id to the associated topics (topicId) quizIds array
const quizIdExists = state.topics[action.payload.topicId].quizIds.includes(action.payload.id);
// avoid adding duplicate quiz ids
if (!quizIdExists) {
state.topics[action.payload.topicId].quizIds.push(action.payload.id);
} else {
console.log('quiz id', action.payload.id, 'already exists');
}
})
},
})
export const selectTopics = state => state.topics.topics; // all topics selector
export const { addTopic } = topicsSlice.actions; // export actions
export default topicsSlice.reducer; // export reducer