1

I want to render list from json data from url on ReactJS THis is the data on loaclhost 10.0.10.10/3000

confused to use axios or fetch

{
  "users": [{
      "_id": "7odGhvEvLBYtQujdZ",
      "createdAt": "2019-07-23T10:48:01.438Z",
      "username": "123",
      "profile": {
        "active": "true"
      }
    },
    {
      "_id": "dgBWJ4qBNx94MketL",
      "createdAt": "2019-07-23T15:33:34.270Z",
      "username": "user1",
      "profile": {
        "active": "true"
      }
    },
    {
      "_id": "hNTnjMEXdn5gbNSGZ",
      "createdAt": "2019-07-23T16:16:56.070Z",
      "username": "user2",
      "profile": {
        "active": "true"
      }
    },
    {
      "_id": "porAsWJ3ba48JnLPd",
      "createdAt": "2019-07-23T10:21:05.541Z",
      "username": "user3"
    },
    {
      "_id": "f6NJpu8rggfGmYJEY",
      "createdAt": "2019-07-30T11:47:54.652Z",
      "username": "usre4",
      "profile": {
        "active": true
      }
    },
    {
      "_id": "anZQB6PsfuatCGxA6",
      "createdAt": "2019-07-30T11:44:55.997Z",
      "username": "user5",
      "profile": {
        "active": true
      }
    }
  ]
}

i want a simple way to dispay this data in list or table in reactJS.

using axios or fetch.

Akshay Mulgavkar
  • 1,727
  • 9
  • 22
  • 1
    This question has been answered before - https://stackoverflow.com/questions/47686011/rendering-list-with-fetch-in-react – goto Jul 31 '19 at 10:33

2 Answers2

1

Use Array.map to render your template for each entry

class ListComponent extends Component {

  constructor(props) {
    super(props);

    this.state = {
      articles: [],
    }
  }


  async componentDidMount() {
    fetch('https://jsonplaceholder.typicode.com/todos/')
    .then(response => response.json())
    .then(json => {
      this.setState({
        articles: json,
      })
    })
  }

  render() {
    return (
      this.state.articles.map(row => <div key={row._id}>{row.username}</div>)
    )
  }

}
Andrei Todorut
  • 4,260
  • 2
  • 17
  • 28
1

You can use any one of them it will work but i feel Axios will be convenient because it has inbuilt .json() method over fetch() and it supports the Promise API that is native to JS ES6.

When you are using fetch() it is a two step process, when handing JSON data. The first is to make the actual request and then the second is to call the .json() method on the response.

And as far as displaying it in React,you can iterate it since it is arraylist, a short example of the same:

<div>
    <ul>{list.map(name => <li key={list._id}> {list.username} </li>)}</ul>
</div>

_map from lodash

const result = _.map(list, function(value, key) {
  return value ;
});

Or you can use for each as well.

techipank
  • 432
  • 4
  • 17