Home > Net >  How to send a data from JavaScript to JSON database with fetch api?
How to send a data from JavaScript to JSON database with fetch api?

Time:08-29

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 >
                            <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?

CodePudding user response:

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();
}
  • Related