Search code examples
javascriptreactjsruby-on-railsfetch-apiactive-model-serializers

ReactJS fetch from Rails API: Return the hash in an array


let user = {  
   "id":14,
   "email":"[email protected]",
   "first_name":"Fry",
   "last_name":"Hamson",
   "posts":[ { id: 28,
    dog_name: 'Skip',
    description: 'yub nub! yub nub!',
    image_url: 'https://www.k9ofmine.com/wp-content/uploads/2014/09/ewok-dog-costume.jpg' },
    { id: 29,
    dog_name: 'Champ',
    description: 'You were my brother! I loved you!',
    image_url: 'http://stories.barkpost.com/wp-content/uploads/2014/04/dog-star-wars-costume-12.jpg' },
    { id: 32,
    dog_name: 'Baxter',
    description: 'Give me treats, you will...',
    image_url: 'http://www3.pictures.zimbio.com/mp/r_Mf-uluvPrx.jpg' } ]

I'm having trouble retrieving the data from the above code snippet. I have the logic all set, but I can't figure out where to place it in my React Component without it breaking. Here's my React page, I have the logic commented out in the fetch.

class Profile extends Component {
  constructor(props){
    super(props);
    this.state = {
      names: [],
      descriptions: [],
      images: []
    }
    this.getProfileData = this.getProfileData.bind(this)
  }

  componentDidMount() {
    this.getProfileData()
  }

  getProfileData() {
    fetch(`/api/v1/users`, {credentials: 'same-origin'})
    .then(response => response.json())
    .then(user => {
      this.setState({
        id: user.id,
        firstName: user.first_name,
        lastName: user.last_name,
        posts: user.posts
    // for (i=0; i<user.posts.length; i++) {
    //   names.push(user.posts[i].dog_name)
    //   descriptions.push(user.posts[i].description)
    //   images.push(user.posts[i].image_url)
    // }
      })
    })
  }

  render() {
    return(
      <div>
        <ProfileTile />
      </div>
    )
  }
}

I know the commented out logic isn't formatted correctly with the setState, as I've moved it around quite a bit, but I'm lost at the moment on how to implement this iteration. I am using active:model:serializers on the Rails side.


Solution

  • If you want names, descriptions, images in the state, you should use the map function to retrieve them.

    getProfileData() {
        fetch(`/api/v1/users`, {credentials: 'same-origin'})
        .then(response => response.json())
        .then(user => {
          this.setState({
            id: user.id,
            firstName: user.first_name,
            lastName: user.last_name,
            posts: user.posts,
            names: user.posts.map(u => u.dog_name),
            descriptions: user.posts.map(u => u.description),
            images: user.posts.map(u => u.image_url)
          });
        });
      }