Home > front end >  React props undefined on receiving
React props undefined on receiving

Time:01-17

I'm having this issue with passing props object that on second page it says it's undefined. I tried if I'm passing it correctly with console.log(databaseObject?.points[0].questions) on first page and it was what I wanted, but when I tried to receive it on second page it's always undefined. Am I missing something on receiving the props or? On second page from console.log(props.questions) I got 'undefined' and from console.log(Object.values(props.questions)) I got TypeError: "Cannot convert undefined or null to object"

first.tsx

interface Point {
  details: string,
  id: string,
  image: string,
  imagePath: number,
  isFirst: boolean,
  isLast: boolean,
  isReady: boolean,
  poiont: object,
  pointTitle: string,
  questions: Question[]
}

interface Question {
  answer1: string,
  answer2: string,
  answer3: string,
  id: string,
  question: string,
  rightAnswer: string
}

interface DatabaseObject {
  points: Point[]
  trailId: string
}

Code below is to redirect to second page

  const redirect = () => {
    history.push({
      pathname: '/user_app/quiz',
      state: databaseObject?.points[0].questions
    });
  }

second.tsx

interface Question {
    answer1: string,
    answer2: string,
    answer3: string,
    id: string,
    question: string,
    rightAnswer: string
  }

interface Props {
    questions: Question[]
  }


const QuizPage: React.FunctionComponent<Props> = (props) =>{
    const history = useHistory();
    const [answered, setAnswered] = useState(false);
    const [correct, setCorrect] = useState(false);
    const [clickedAnswer, setClickedAnswer] = useState('');
    const coreectAnswer = 'odpoved1'

    useEffect(() =>{
        console.log(props.questions)
        console.log(Object.values(props.questions))
        checkAnswer()
    })

CodePudding user response:

You have passed a location object to history.push so the component can find the corresponding state there.

useEffect(() =>{
  console.log(props.location.state.questions)
  console.log(Object.values(props.location.state.questions))
  checkAnswer()
})

CodePudding user response:

props is not available in useEffect scope. You must pass it as a dependency in useEffect.

Try following:

 useEffect(() =>{
        console.log(props.questions)
        console.log(Object.values(props.questions))
        checkAnswer()
    }, [props])
  •  Tags:  
  • Related