0

https://github.com/smelukov/loftschool-example i am creating my project in this envorement .

I created friends.json file in the root folder .

friends.json

    {
        "name": "Иван",
        "lastName": "Петров",
        "value": "5.24"
    },
    {
        "name": "Иван",
        "lastName": "Петров",
        "value": "6.00"
    },
    {
        "name": "Иван",
        "lastName": "Петров",
        "value": "4.54"
    }
]

index.hbs

<div id="prev-results"></div>

<button id="loadButton">Load Results</button>

index.js

const loadButton = document.querySelector("#loadButton");
const result = document.querySelector('#prev-results');
 
loadButton.addEventListener('click', () => {
    fetch('friends.json')
        .then(response => {
            if (response.status >= 400){
              return Promise.reject();
            }

            return response.json();
        })
        .then(friends => {
                result.innerHTML = '';
                for (let friend of friends) {
                    const friendNode = createFriendNode(friend);
                

                    
                    result.appendChild(friendNode);

                }
        })
        .catch(() => console.error('Что-то пошло не так'));
});
 
function createFriendNode(friend) {
    const div = document.createElement('div');
    
    
    div.classList.add('friend');
    div.textContent = `${friend.name} ${friend.lastName}`;

    const result = document.createElement("a");
    result.textContent = `${friend.value}`;
    result.classList.add("result");

    const label = document.createElement("a");
    label.classList.add("result-label")
    label.textContent = "mL/min/1.73m²";

    div.appendChild(result);
    div.appendChild(label);
    return div;
}

Now i can get objects from friends.json and add them to the DOM , but how do i change friends.json with javascript ?

1 Answers1

1

The client can't write back to the static file it's being served. This would be the use case for a database. For a JSON-like document object store that can be manipulated, you can use something like MongoDB.

C. Slack
  • 111
  • 1
  • 3
  • 1
    Or simply send a request to your back-end that changes the file? Db is surely the best way to go about this issue, but he specifically asked how to change the JSON file, which this doesn't answer it. – Art3mix Mar 08 '21 at 23:07
  • 1
    There is only front end code here. Hence my answer that it's not possible. I wasn't going to go so far as to explain how to set up a back end api to change the file. In which case he would essentially be using the static file as a database and he should instead use an actual database to get the functionality he wants in a more practical way. – C. Slack Mar 09 '21 at 01:44