So I am trying to create a simple array that lists all the items that have been mapped. All other options around here seem much to complex for what I'm trying to do.
The code that gets my data is:
componentDidMount() {
fetch('http://localhost:9000/api/get/locations')
.then(res => res.json())
.then(res => {
if (res && res.data) {
this.setState({ apiResponse: [...this.state.apiResponse, ...res.data] })
}
});
}
I can them map it into something like a list using this code:
getLocations() {
if (this.state.apiResponse.length <= 0) {
return <div>Loading...</div>
} else {
return this.state.apiResponse.map((val, key) => {
return <li key={key}> {val.name} </li>
})
}
}
However, I want to have an array that such as "locations" So that each value is mapped to an item in an array.
Example (of code that would not work):
const locations = []
setLocations() {
if (this.state.apiResponse.length <= 0) {
return <div>Loading...</div>
} else {
return this.state.apiResponse.map((val, key) => {
return locations = [...locations, ...{id: key, value: val.name, isChecked=false}]
})
}
}
# Output:
locations = [
{id: 1, value: "val1", isChecked=false},
{id: 2, value: "val2", isChecked=false},
{id: 3, value: "val3", isChecked=false},
{id: 4, value: "val4", isChecked=false}
]
Is there a way to do this simply? or another way to go around doing it?