'How to change picture in JavaScript on button click when using a mock JSON server?

I have a 'db.json' file and this file has data relating to images for the different Star Wars characters which was pulled from the Star Wars API.

I used this in my 'script.js':

function getPeople() {

let numberPeople = Math.floor((Math.random()*83)+1)
let apiUrl = 'https://swapi.dev/api/people/' +  numberPeople 

fetch(apiUrl)
.then(function(response){
    return response.json()
})
.then (function(json){
    console.log(json)
    let name = document.getElementById('name')
    let DOB = document.getElementById('DOB')
    let height = document.getElementById('height')
    let weight = document.getElementById('weight')
    let gender = document.getElementById('gender')

    name.innerText = `Name: ${json['name']}`;
    DOB.innerText = `Date of Brith: ${json['birth_year']}`;
    height.innerText = `Height: ${json['height']} cm`;
    weight.innerText = `Weight: ${json['mass']} kg`;
    gender.innerText = `Gender: ${json['gender']}`;

    
    fetch(`${json['homeworld']}`)
    .then(function(response) {
        return response.json()
    })
    .then(function(json) {
        console.log(json)
        let homeWorld = document.getElementById('home-world')

        homeWorld.innerText = `Home Planet: ${json['name']}`;
    })

fetch('./db.json')
        .then(results => results.json())
        .then(data => {
            console.log(data.people)

            var url = data.people[numberPeople-1]['imgUrl']
            var image = new Image();
            image.src = url

            
            document.getElementById('header').appendChild(image)

        })

The code in question start with "fetch('/db.json)" so the 'numberPeople' variable just pertains the id of the character. For example, Luke Skywalker, his url is https://swapi.dev/api/people/1, my webpage has randomised the number aspect so that on each click a new number is made getting a different character.

The mock JSON server (db.json) that was made has url's for pictures and via DOM manipulation depending on the 'numberPeople' variable will append the image depending on the character.

My problem is that when I click the button:

peopleButton.addEventListener('click', getPeople)

The pictures corresponds correctly with the character however, when I click it again the new picture is there as well as the previous picture. I tried different solutions but, I am not sure how to go about it when dealing with a JSON server.

Is there a way I can go about it? I am new to using JSON servers and any help would be great.



Solution 1:[1]

Pleas read here about replaceChild:

https://developer.mozilla.org/en-US/docs/Web/API/Node/replaceChild

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tom