'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>
);

}


Solution 1:[1]

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;

Solution 2:[2]

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}/>
}

Solution 3:[3]

Look for the code in your Axios interceptor

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 carrany
Solution 2 Arnav Borborah
Solution 3 JAMES xie