0

I need to append this data response example in my React app.

DATA Response

[
  {
    "trackInfo": {
      "id": 1,
      "title": "Guns & Dogs",
      "artist": "Portugal, The Man",
      "album": "The Satanic Satanist"
    },
    "trackUrl": "https://s3-us-west-2.amazonaws.com/teddarcuri.monarch/Portugal.+The+Man+-+Guns+%26+Dogs+-+The+Satanic+Satanist.mp3",
    "albumArt": "http://ecx.images-amazon.com/images/I/61X7CiBpZ6L.jpg"    
  }
]

React JS

class App extends React.Component {
  constructor(props){
    super(props)
    this.state = { //initial empty details
      details : {}
    }
  }
  componentDidMount(){
    //place the ajax call where ever you need
    $.ajax() //call ajax
    .done((data) => {
      this.setState({ //this setState will re render the UI with the new state
        details: { //change the key value pairs as needed
          id: data.id,
          trackInfo: {
            title: data.title,
            artist: data.artist,
            album: data.album,
          },
          trackUrl: data.trackUrl,
          albumArt: data.albumArt,
        }
      })
    })
  }
    render() {
      if(!this.state.details.id) return false //renders nothing when no details available
        return (
            <div id="app">
                <MusicPlayer
                    id={this.state.details.id}
                    visualizerType="RIPPLES"
                    theme={darkTheme}
                    trackInfo={this.state.details.trackInfo}
                    trackUrl={this.state.details.trackUrl}
                    albumArt={this.state.details.albumArt}
                    utilities={true}>
                </MusicPlayer>
            </div>
        )
    }
}

ReactDOM.render(
    <App />,
    document.getElementById("app")
);
  • Full code example here
  • Working example with preloaded data here

So my question is, how can I append the new data in React using Ajax?

A code example will be really appreciate, thanks.

NineCattoRules
  • 2,253
  • 6
  • 39
  • 84
  • 1
    Your example is not JSON. It's a broken JavaScript string. Can we assume that you get the data without problems and `data` is the object you expect? Either way, the problem is not about JSON. – Felix Kling Nov 02 '16 at 13:34
  • Currently your component *overwrites* the current state with the new data. Do you want to render a list of `MusicPlayer`s instead of a single one? – Felix Kling Nov 02 '16 at 13:36
  • 1
    Based in your information, the response you get is an *array* of objects, but you are treating `data` as an object. Is that the issue maybe? Can you explain what the problem is with your code? – Felix Kling Nov 02 '16 at 13:38
  • @FelixKling this is probably a silly request but I'm not able to get the data(I don't know how to append from the JSON). If you click on "Full code example" you'll see a blank page – NineCattoRules Nov 02 '16 at 13:39
  • 1
    *Append* means adding to an existing list. You don't have a list. So you either a) want to change your component to render a list (currently you don't) or b) you are using the wrong terminology and what you want is to get the above code working. – Felix Kling Nov 02 '16 at 13:43
  • As I said in a comment, according to your information, `data` is an **array**, but you are treating it as an object. Simple example: `var data = [{id: 42}];`. `data.id` is `undefined` because arrays don't have such a property. This is what you are doing. Correct would be: `data[0].id`, which successfully accesses the `id` property of the first element of the array. I believe this is a duplicate of [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/q/11922383/218196) – Felix Kling Nov 02 '16 at 13:45
  • 2
    `` is just a single component. There is no list. A list would be if you rendered multiple `MusicPlayer`. – Felix Kling Nov 02 '16 at 13:47

1 Answers1

3

I think you want to show a list of MusicPlayer, so I changed your code: [you need to read more about state in react]

class App extends React.Component {
  constructor(props){
    super(props)
    this.state = { //initial empty details
      details : []  // use array
    }
  }
  componentDidMount(){
    //place the ajax call where ever you need
    $.ajax() //call ajax
    .done((data) => {
      let array = this.state.details;
      array = [...array, {
          id: data.id, 
          trackInfo: {
            title: data.title,
            artist: data.artist,
            album: data.album,
          },
          trackUrl: data.trackUrl,
          albumArt: data.albumArt,
      }];
      this.setState({
        details: array
      })
    })
  }
    render() {
      if(!this.state.details.id) return false //renders nothing when no details available
        return (
            <div id="app">
                {
                    this.state.details.map((detail) => {
                        return <MusicPlayer
                    id={detail.id}
                    visualizerType="RIPPLES"
                    theme={darkTheme}
                    trackInfo={detail.trackInfo}
                    trackUrl={detail.trackUrl}
                    albumArt={detail.albumArt}
                    utilities={true}>
                </MusicPlayer>
                    });
                }
                
            </div>
        )
    }
}

ReactDOM.render(
    <App />,
    document.getElementById("app")
);
disorderdev
  • 1,458
  • 1
  • 14
  • 28