I am using fetch to get "api.github.com/users" data to show on the screen. I am able to show a single entity but not the entire data. I am new so a bit of detailing will be a great help.
const btnn = document.getElementById("dog");
function Cat(){
fetch('https://api.github.com/users').then(res => res.json())
.then(data => btnn.map((values) =>{
`</p>login:"${values.login}" </p>`})
)}
Cat()
HTML
<body>
<div id="dog"></div>
<button id="btn">Dogs</button>
<script src="api.js"></script>
</body>
CodePudding user response:
You should be looping over data
, not btnn
. btnn
is where you want to display the result of mapping.
map()
returns an array, you should use join()
to concatenate them into a string with the HTML you want to show.
const btnn = document.getElementById("dog");
function Cat() {
fetch('https://api.github.com/users').then(res => res.json())
.then(data => btnn.innerHTML = data.map((values) => `<p>login:"${values.login}" </p>`).join(''))
}
Cat()
<div id="dog"></div>
CodePudding user response:
If your intent is to add new elements to #dog
, you can map your data to an array of elements and append them
const createElement = (tag, textContent) => Object.assign(
document.createElement(tag), { textContent })
const btnn = document.getElementById("dog")
function Cat() {
fetch('https://api.github.com/users')
.then(res => res.json())
.then(data => { // assuming data is an array
btnn.append(...data.map(({ login }) => createElement("p", `login:${login}`)))
})
}
Cat()
<div id="dog"></div>