1

Inside my userDB.json file it looks like this;

[{
    "username": "john",
    "xp": 5
},
{
    "username": "jane",
    "xp": 0
}
]

Inside the app.js file ;

async function getUsers() {
    let url = 'userDB.json';
    try {
        let res = await fetch(url);
        return await res.json();
    } catch (error) {
        console.log(error);
    }
}

async function addUser(username){
    let users = await getUsers();

    let newUser = {"username": `${username}`,"xp": 0};
    users.push(newUser);
}

addUser('testName');

async function renderUsers() {
    let users = await getUsers();
    let html = '';
    users.forEach(user => {
        let htmlSegment = `<div class="user">
                            <h2>${user.username} ${user.xp}</h2>
                        </div>`;

        html += htmlSegment;
    });

    let container = document.querySelector('.container');
    container.innerHTML = html;
}
renderUsers();

I would like to send a data to my local database and save it then I would like to render database array items on screen. But when I console.log the users in addUser() function added item visible on console but not rendered or saved on local file how to do that?

2
  • not rendered or saved on local file how to do that? - local file where? If this code is running in a web browser, you will need some actual server-side code to modify files on the server. If this code is running some other environment than a browser, please specify. Commented Aug 28, 2022 at 16:12
  • 1
    @tevemadar yeah I made a mistake about server side and browser I understood now thanks Commented Aug 28, 2022 at 20:40

1 Answer 1

1

What you are doing in addUser() is to get the array from your database, mutating it by pushing a new item in it, but that only affects that specific array you got, not the database.

For this to work you need to make a post request to a backend that would update your database and then call renderUsers() to get the updated data:

async function addUser(username) {
  let url = "/"; // ⚠️ whatever url that accept a post request
  let newUser = { username: username, xp: 0 };
  await fetch(url, { method: "POST", body: JSON.stringify(newUser) });
  renderUsers();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.