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.
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>
);
}
.then
to get the inner value? I'm also unsure whether you're returning the value correctly from the original function because I think you need areturn
inside the callback in the return statement (stackoverflow.com/questions/42831393/…). – Arnav Borborah<Questions response={reviewAPI.getQuestions()} setData={setData} formData={formData}/>
– ssk<Questions response={reviewAPI.getQuestions().then(function(value){return value})} setData={setData} formData={formData}/>
– sskreturn axios.get(url).then(response => return response.data)
combined with what is done in @Ahmed's answer. – Arnav Borborah