'JSON to Dropdown in React - response.data.map is not a function
I am following the code: https://codesandbox.io/s/cranky-leaf-2hupv?fontsize=14&hidenavigation=1&module=%2Fsrc%2FApp.js
The example works in my React project but when I try to adapt it to values from my database, I get the error:
Uncaught (in promise) TypeError: response.data.map is not a function
My JSON is simple
categories:
0:
Id: "22"
Name: "Strategy"
1:
Id: "19"
Name: "Sports"
2:
Id: "27"
Name: "Branding"
I have adapted the code to fit my JSON as follows:
import React, { Component } from 'react';
import axios from 'axios';
export default class TestDropdown extends React.Component {
constructor(props) {
super(props);
this.toggle = this.toggle.bind(this);
this.state = {
display: "",
titles: [],
errorMsg: ''
};
}
toggle() {
this.setState(prevState => ({
dropdownOpen: !prevState.dropdownOpen
}));
}
componentDidMount = (e) => {
axios.get("https://mysite/devapi/categories.php").then((response) =>
this.setState({
titles: response.data.map(({ Name }) => Name), /*error*/
display:
response.data[Math.floor(Math.random() * response.data.length)].title
})
);
};
render() {
const { display, titles } = this.state;
return (
<div className="container">
<select defaultValue={display}>
{titles.map((Name) => (
<option key={Name} value={Name}>
{Name}
</option>
))}
</select>
</div>
);
}
}
I have considered whether I am making a mistake by reading the wrong JSON value by not accessing 'categories' or whether this has something to do with map / list. I would only need the Name values to populate the Option with.
Kind thanks from a beginner.
Solution 1:[1]
You can try do something like
response?.data?.map(({ Name }) => Name)
or
response && responese.data && response.data.map((element, index) => {
console.log('My data', element) // here you should see your data
})
To make sure, that we have that data
Have fun!
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 |
