Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

128
Views
How to send a data from JavaScript to JSON database with fetch api?

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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();
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!