Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

131
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda