ssk
ssk

Reputation: 317

Axios Uncaught TypeError: Cannot read property 'map' of undefined

I'm trying to display data from my API in a React App with Axios.

I've created a simple method that connects to the REST API.

import axios from 'axios';
const API_URL = 'http://127.0.0.1:8888';

export default class ReviewAPI{
    getQuestions(title) {
        const url = `${API_URL}/api/questions/?title=${title}`;
        return axios.get(url).then(response => response.data);
    }
}

When I make the API call it returns back the response but as a Promise.

enter image description here

When I try to map through the response I get `cannot read property map of undefined'

export default function Questions({ response, setData, formData}) {
return (
    <Card className="m-3">
        <Card.Header>{response.description}</Card.Header>
        <Card.Body>
            { response.questions.map((question, idx) => {
                switch (question.type) {
                    case "text": return <FormText key={idx} question={question} setData={setData} formData={formData}/>;
                    case "textarea": return <FormTextArea key={idx} question={question} setData={setData} formData={formData}/>;
                    case "radio": return <RadioGroup key={idx} question={question} setData={setData} formData={formData}/>;
                    case "multiselect": return <MultiSelect key={idx} question={question} setData={setData} formData={formData}/>;
                    default: return [];
                }
            })}
        </Card.Body>
    </Card>
);

}

Upvotes: 0

Views: 226

Answers (3)

JAMES xie
JAMES xie

Reputation: 1

Look for the code in your Axios interceptor

Upvotes: 0

carrany
carrany

Reputation: 156

rewrite it like so:

getQuestions(title) {
            const url = `${API_URL}/api/questions/?title=${title}`;
            let data;
             axios.get(url).then(response => {data = response.data});
           return data
        }

when you call the reviewAPI.getQuestions(), all you will get is the data returned;

Upvotes: 1

Ahmed Khattab
Ahmed Khattab

Reputation: 2799

You need to await the promise before you can map over the items.

In a functional component you need to do this:

const questions = () => {
  const [questions, setQuestions] = useState([]);

  useEffect(async () => {
       const res= await reviewAPI.getQuestions();

       setQuestions(res.data);
   }, []);

   return 
      <Questions 
         response={questions} 
         setData={setData} 
         formData={formData}/>
}

Upvotes: 0

Related Questions