0

I have a react app with redux for state management on the frontent. My top level component fetches data from firebase and sets the state:

 useEffect(() => {
    dispatch({ type: 'FETCH_ALL_QUESTIONS' })
  }, [dispatch]);

  useEffect(() => {
    dispatch({ type: 'FETCH_USERS'})
  }, [dispatch]);
  

For example question page uses questions from the state.

  const userLoggedIn = useSelector(state => state.loggedIn)
  const selectedQuestion = useSelector(state => state.selectedQuestion);
  const questions = useSelector(state => state.questions)
  const myQuestion = questions.find(q => q.id === selectedQuestion.id);
  const answers = myQuestion.answers;

But when I reload that question page, the entire state is returned to its initial state. At that point question page crashes the entire app and the state is not fetched again. Is there a way to aviod this?

1 Answers1

0

You can add condition as:

const questions = useSelector(state => state.questions ? state.questions : [])
const myQuestion = questions.find(q => q.id === selectedQuestion.id);
const answers = myQuestion && myQuestion.length > 0 ? myQuestion.answers : null;
Abin Thaha
  • 4,493
  • 3
  • 13
  • 41