DEV Community

agentggg
agentggg

Posted on

How to present Axios data as list

I have an API request from my backend to ReactJS frontend. The results is presented in JSON format. When the user press the "submit" button, I want the JSON data only for a specific key of the array of each object to presented to the user in nice list format.

  • First code snippet is the JSON code

  • Second code is my AXIOS code

  • Third code is my ReactJS frontend code with the button and etc.

  • The picture is how it looks when the user press the button. I need it in list format. Meaning each entry on a new line. Currently it jumbos everything to one list

Any thoughts?

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  },
  {
    "userId": 1,
    "id": 3,
    "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
    "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
  }
Enter fullscreen mode Exit fullscreen mode
const App = () =>{
  const [buttonTitle, setButtonTitle] = useState("User Data Prior To Change")

    const getAPI = ()=>{
      const loopList = []
      const url = "https://jsonplaceholder.typicode.com"

      axios.get(`${url}/posts`)
      .then((response)=>{
            const myValue = response.data
             myValue.forEach(myValueValues => {loopList.push(myValueValues['title'])})
             setButtonTitle(loopList)
          })
        .catch(error => console.error(`Error: ${error}`))
      }

Enter fullscreen mode Exit fullscreen mode
        <h1>Click button to see list of user</h1>
        <button onClick={getAPI}>Button to press to see all info in clean format
</button>
        <ul>
          <li>{buttonTitle}</li>
        </ul>

Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (0)