Abena
Abena

Reputation: 1

TypeError: Cannot find property of undefined

I'm trying to fetch data from an api using react hooks useEffect. I'am able to get the data but i'm unable to map the data to obtain its property. This is my code below

useEffect(() => {
    async function fetchMyAPI() {
        const response = await fetch('http://localhost:3000/api/questions');
        const question1 = await response.json();
        const question = question1.map((question, i) => question[i].questions_text);
        setQuestion(question);
        console.log(question);
    }

    fetchMyAPI();
}, [])`

error: const question = question1.map((question, i) => question[i].questions_text);

modification but i want to able to get a single question: const question = question1.map((question, i) => question.questions_text);

const question = question1.filter((question, i) => i===2 && question.questions_text);

Upvotes: 0

Views: 209

Answers (1)

Mr.M
Mr.M

Reputation: 106

I don't know the context of your problem, but I think you are a facing a common problem in react. I believe that somewhere in your code you are trying to render a component that depends on question data. on the first render, "question" does not have any value so if your component is trying to access question.id for example, you will get Cannot find property of undefined.

To solve this issue, add a default value for the question object .

Upvotes: 1

Related Questions