Search code examples
reduxreact-reduxuse-effect

React Redux useEffect not loading data on initial page render


I'm trying to render a quiz object from an api and am using useEffect to do so, but it doesn't seem to be working.

Here is my Quiz component:

export function Quiz(props) {
  const { 
    quiz, 
    fetchQuiz,
  } = props;

  useEffect(() => {
    fetchQuiz();
  }, [])

  return (
    <div id="wrapper">
      { quiz.question }
    </div>
  )
}

const mapStateToProps = state => {
  return {
    quiz: state.quiz,
  }
}

export default connect(mapStateToProps, {
  fetchQuiz,
})(Quiz)

my action creator:

export function fetchQuiz() {
  return function (dispatch) {
    axios. get('http://localhost:9000/api/quiz/next')
        .then(res => {
          dispatch({ type: SET_QUIZ_INTO_STATE, payload: res.data })
        })
        .catch(err => console.error(err))
    }
}

my reducer:

const initialQuizState = null
function quiz(state = initialQuizState, action) {
  switch(action.type) {
    case SET_QUIZ_INTO_STATE:
      return action.payload
    default:
      return state
  }
}

So when I console.log "quiz" in my Quiz component, I get the object that I am expecting and it's all good. But when I try and call "quiz.question" I get the error: Cannot read properties of null (reading question). Which leads me to believe useEffect is not loading the data from the api correctly. Am I doing something else wrong?


Solution

  • When accessing an object from an API response in the DOM, make sure you have a conditional to check for completion like so:

      return (
        <div id="wrapper">
          { quiz ? quiz.question : 'No Quiz Here' }
        </div>
      )
    }