I have a reducer that set the state for a quiz App(MERN Stack). it basically loads the quiz question from the database. When I start the application with data inside the reducer, everything works perfectly, but whenever I transfer the data to the database, I get the error of “undefined”
I tested my backend with postman before connecting to redux, it worked perfectly. Below are the code snippet
class QuestionApp extends Component {
constructor(props) {
super(props);
this.state = {
counter: 0,
questionId: 1,
question: '',
answerOptions: [],
answer: '',
answersCount: {
Smart: 0,
Subpar: 0,
Confused: 0
},
result: ''
};
this.handleAnswerSelected = this.handleAnswerSelected.bind(this);
}
componentDidMount() {
this.props.getQuiz();
const shuffledAnswerOptions = this.props.quiz.quizes.map((question) =>
this.shuffleArray(question.answers));
this.setState({
question: this.props.quiz.quizes[0].question,
answerOptions: shuffledAnswerOptions[0]
});
}
//QuizReducer
import{GET_QUIZ,QUIZ_LOADING } from '../actions/types'
const initialState = {
quizes : [],
loading: false
}
export default function(state=initialState,action){
switch(action.type){
case GET_QUIZ:
return{
...state,
quizes:action.payload,
loading:false
}
case QUIZ_LOADING:
return{
...state,
loading:true
}
default:
return state;
}
}
QuizAction.js
import axios from 'axios'
import{GET_QUIZ,QUIZ_LOADING} from './types';
export const getQuiz =()=>dispatch=>{
dispatch(setQuizLoading());
axios
.get('/api/quizes')
.then(res=>
dispatch({
type:GET_QUIZ,
payload: res.data
})
)
};
export const setQuizLoading =()=>{
return{
type:QUIZ_LOADING
}
}
//Quiz Question
quizes= [
{
question: "What is 4 X 4 ? ",
answers: [
{ type: "Smart",content: "16" },
{
type: "Subpar",
content: "15"
},
{
type: "Confused",
content: "1"
}
]
},
// My Schema
const QuizSchema = new Schema({
question: {
type:String,
default:''
},
answers: [{
type: {
type: String,
default:''
},
content: {
type: String,
default:''
},
}],
});
I expect the initial state to be populated with data from the database, but this is the error I get : TypeError: Cannot read property ‘question’ of undefined