I have below JSON file. There is an Array(answers) inside that JSON. I want to map and render them.
{
"qID": "177",
"myQuestion": true,
"qContent": "testing",
"answers": [{
"anonymous": true,
"aID": "184",
"aContent": "test",
"aDate": "Mon, 14 Sep 20 06:47:38 +0000",
"myAnswer": false,
"authorName": "abc",
"aFeaturedImg": "..\/uploads\/407378vk053.jpg",
"authorImg": "https:\/\/lh3.googleusercontent.com\/a-\/AOh14GjhhO-11Wktws9-FXBZoWk3vT8tRM2Sy7IQ4cnpw=s96-c"
},
{
"anonymous": true,
"aID": "184",
"aContent": "test",
"aDate": "Mon, 14 Sep 20 06:47:38 +0000",
"myAnswer": false,
"authorName": "abc",
"aFeaturedImg": "..\/uploads\/407378vk053.jpg",
"authorImg": "https:\/\/lh3.googleusercontent.com\/a-\/AOh14GjhhO-11Wktws9-FXBZoWk3Cv8tRM2Sy7IQ4cnpw=s96-c"
}
]
}
my react code like this. I want to use state
function Question({ match }) {
useEffect(() => {
fetchItem();
}, []);
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ qID: match.params.id })
};
const [item, setItem] = useState([]);
const fetchItem = async () => {
const data = await fetch('https://example.com/api/getAnswer.php' , requestOptions);
const item = await data.json();
setItem(item);
};
return (
<Container maxWidth="sm">
{item.answers.map(answer => (
<Card key={answer.qID}>{answer.qContent}</Card>
))}
</Container>
);
}
export default Question; But This not work. It gives following error
TypeError: Cannot read property 'map' of undefined
console.log(item.answers)just before the render? and is this json data coming from ajax? then how youritemstate looks like?