Oops! Encounterred a TypeError stating "Unable to access properties of an undefined object" while working with react native

Within my React Native Quiz function, I have implemented a fetch GET request to load data. Upon checking if the data has loaded using the showQuestion variable, I encounter an error message:

Cannot read properties of undefined (evaluating 'questObj[currentQuestion].questionText')

I attempted to print the data using questObj[currentQuestion], which reveals an object filled with data. The image below showcases the result of the console.log.

  console.log(questObj[currentQuestion]);

https://i.sstatic.net/d0Y5A.png

Any insights on where I might be going wrong? (Given my novice status in React Native, it could very well be due to a fundamental mistake from my end.)

export function Quiz(this: any) {
  const styles = StyleSheet.create({
    container: {
      backgroundColor: '#B86566',
      width: '100%',
      height: '100%',
      alignItems: 'center',
      justifyContent: 'center'
    },
    headingColumn: {
      flexBasis: '90%',
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      flex: 1,
      padding: 20,
      fontSize: 30,
    },
    buttonColumn: {
      flexBasis: '35%',
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      flex: 1,
      padding: 20,
      margin: 20,
      borderColor: 'white',
      borderWidth: 1
    },
    row: {
      display: 'flex',
      flexDirection: 'row',
      flexWrap: 'wrap',
      width: '100%'
    },
  });
  const [showScore, setShowScore] = useState(false);
  const [showQuestion, setShowQuestion] = useState(false);
  const [currentQuestion, setCurrentQuestion] = useState(0);
  const [score, setScore] = useState(0);
  const [questionArray, setQuestions] = useState(0);

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

  let questObj: {
    questionText: any;
    answerOptions: any;
  }[] = [];

  const getQuestions = async () => {
    try {
      let response = await fetch(
        'https://opentdb.com/api.php?amount=10&category=26&difficulty=medium&type=multiple'
      );
      let json = await response.json();
      json.results.forEach((element: { question: any; correct_answer: any; incorrect_answers: any; }) => {
        questObj.push({
          questionText: element.question,
          answerOptions: [{ answerText: element.correct_answer, isCorrect: true },
          { answerText: element.incorrect_answers[0], isCorrect: false },
          { answerText: element.incorrect_answers[1], isCorrect: false },
          { answerText: element.incorrect_answers[2], isCorrect: false }
          ],
        },
        );
        console.log(questObj[currentQuestion]);
        setShowQuestion(true);
      });

    } catch (error) {
      console.error(error);
    }

  }

  const handleAnswerButtonClick = (isCorrect: boolean) => {
    if (isCorrect) {
      setScore(score + 1);
    }
    const nextQuestion = currentQuestion + 1;
    if (nextQuestion < questObj.length) {
      setCurrentQuestion(nextQuestion);
    } else {
      setShowScore(true);
    }
  };

  return <View style={styles.container}>
    <View><Text></Text></View>
    <View>{showScore ?
      <Text>You scored {score} out of {questObj.length}</Text>
      : <></>}
    </View>
    {showQuestion ?
      <View>

        <View >
          <Text>Question {currentQuestion + 1}/{questObj.length} </Text>
        </View>

        <View style={styles.row}>
          <Text style={Object.assign(styles.headingColumn)}>{questObj[currentQuestion].questionText}</Text>
        </View>
        <View style={styles.row}>
          {questObj[currentQuestion].answerOptions.map((answerOption: { answerText: string; isCorrect: boolean; }, index: any) => (
            <Text style={Object.assign(styles.buttonColumn)}>
              <Button
                title={answerOption.answerText}
                onPress={() => handleAnswerButtonClick(answerOption.isCorrect)}
                color="#fff">
              </Button>
            </Text>
          ))}
        </View>
      </View>
      : <></>}
  </View>;
}

Answer №1

Utilizing react requires careful consideration when handling data sources and state management. The useState() hook serves as a crucial tool for managing state effectively.

In most cases (with some exceptions), all data manipulation should be handled using the useState() hook to ensure proper rendering and updates in the DOM.

Without implementing useState(), React may not detect changes in the data being rendered, leading to potential issues with object recognition within JSX components.

Additionally, it is important to accurately select the state corresponding to the currentQuestion. Depending on your approach, looping through an array of objects or utilizing array indexes can impact how you identify the current question object.

Best of luck!

Here's a revised version incorporating the correct usage of useState():

export function Quiz(this: any) {
      // Code snippet showcasing the correct implementation of useState() hook
    }
Link to source: https://stackoverflow.com/questions/70712396/error-undefined-is-not-an-object-in-react-native#

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide on retrieving styled text from a database and displaying it in TinyMCE

I am encountering an issue where I need to retrieve formatted text from a database and display it in my TinyMCE editor. The content stored in the database looks like this: <p style="text-align: justify;"><strong>Zdrav&iacute;m</strong ...

An effective way to retrieve a property from an observable by utilizing a pipe

I'm having trouble storing an OrderState object in my ngrx store and extracting data from it for my UI using the async pipe. Specifically, I want to retrieve a child property from this observable object. order.state.ts export interface OrderState { ...

How to extract key-value pairs from an object in a TypeScript API request

I am trying to extract the data '"Cursed Body": "100.000%"' from this API response using TypeScript in order to display it on an HTML page. Can anyone help me figure out how to do this? API Response { "tier": &q ...

Change the keys of the object in the return statement

Scenario Imagine a scenario where a method called matter is returning an object in the form of return {content, data} Issue There is a conflict when the method is called a second time, as it overwrites any previous variables that were set from the return ...

I recently created a JavaScript slideshow, but I'm unsure how to properly transition between my images

My slideshow using javascript is transitioning pictures too quickly. I am interested in incorporating a delay to make the image changes smoother. I did some research on stackoverflow and found that many people use JQuery for this purpose, but I'm not ...

What is the best way to set up a session using jQuery?

I've been troubleshooting my code and I can't seem to figure out why the jquery.session.js file isn't working. Can someone help me find a solution? $.session.set('rmng_time', remaining_seconds); alert("j session "+$.sessi ...

including a collection of values into a JSON data structure

Currently, I am iterating through some JSON data (grouped tweets from Twitter) to tally the frequency of specific keywords (hashtags) in order to generate an organized list of common terms. this (19) that (9) hat (3) I have achieved this by initial ...

Identifying a user's unique identity through a POST request using Node.js

Currently, I am developing a browser game that integrates voice communication. To capture audio within the browser, I have chosen to use wami-recorder. This tool relies on Flash technology to make a POST request to the server containing the recorded audio. ...

Protractor: The top tool for testing AngularJS applications

Protractor is a comprehensive testing framework designed specifically for Angular applications, utilizing WebDriverJS as its foundation. As someone who is just beginning to explore web testing, I am curious about the benefits of choosing Protractor over u ...

Reacting to the content within a directory through a dynamic TreeView

I am working on displaying the content of a directory inside a material TreeView while parsing it. Here is my current progress: const displayDirectoryContent = (path: string) => { fs.readdir(path, (_: any, elements: any) => { elements.forEach(( ...

Troubleshooting TypeScript errors in a personalized Material UI 5 theme

In our codebase, we utilize a palette.ts file to store all color properties within the palette variable. This file is then imported into themeProvider.tsx and used accordingly. However, we are encountering a typescript error related to custom properties as ...

Concern with generic characteristics during type conversion

One of the utilities in my library is a type similar to the following: type Action<Model extends object> = (data: State<Model>) => State<Model>; This utility type allows the declaration of an "action" function that operates against a ...

The process of dynamically adding a property to the parameter of the React setState method

In my project, I utilize reactjs and typescript. Here are the lines of code I am using: if (reinitGridState) { this.setState({ isbusy: false, itemsList: data, colList: columns, gridState: this.initGridState, gri ...

MUI input remains static and unaltered

I tried to switch from my regular input to a Material-UI text field. Everything was working fine before, but now the value isn't changing. const handleChangeInput = (e) => { const { name, value } = e.target; console.log(e.target.value); ...

Not all divs are triggering the hover event as expected

I am facing an issue while creating a webpage with overlapping background and content divs. The hover event works properly on the div with the class "content," but not on the div with the class "background." There is no interference with the event in the J ...

Implementing jQuery to add content within Redactor

I am working with a textarea field that has an ID of "description", however, it is being rendered by a WYSIWYG editor called Redactor. I am trying to use jQuery to input something in the textarea. So far, I have attempted: $('#description') ...

Creating a State in Typescript Vuex with Accessors: A Step-by-Step Guide

Within the vuex store, I am attempting to initialize a state called _token. However, when I try to access the property within the same class, I am encountering an error message stating that the setter for _token is not defined. Can anyone shed light on why ...

Having difficulty with pagination within a callback function

I have been attempting to paginate in a call to a callback function, but I am encountering an error on the second call. Here is what my function does: let content = '' let size = 100 let from = 1 function result(size, from, callback) { ap ...

Showcase data objects in JSX format

I have an Object stored in my state that looks like this: console.log(state) I've developed a component to display a card for each item within this object (which contains sub-objects). Despite trying multiple approaches, I keep encountering an error ...

Creating personalized features on Three.js models: Geometry's custom attributes

I have been grappling with an issue while using Three.js. I am trying to pass a custom attribute to my shader, which needs frequent updates. The shader is set as a ShaderMaterial for my mesh. However, the problem I am facing is that Three.js has recently ...