0

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?

2 Answers 2

1

You can take the desired output using a map like this, in fact this the basic usage of map,

setLocations() {
    if (this.state.apiResponse.length <= 0) {
      locations = [];
    } else {
      locations = this.state.apiResponse.map((val, key) => {id: key, value: val.name, isChecked=false});
    }
  }

this will give an output like this:

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

please let me know if you need more information.

Sign up to request clarification or add additional context in comments.

2 Comments

This works, however, I need to set the locations to a state, doing this.setState({items: locations}) gives me a 'maximum depth exceeded' error, even though this function is only called once
I am afraid, this looks like another issue in you code, did you try - stackoverflow.com/questions/48497358/…. could you please select this as the correct answer.
0

Try this instead:

this.state.apiResponse.map((val, key) => {
        return locations = [...locations, ...[{id: key, value: val.name, isChecked=false}]]
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.