Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mapping data form database to an array of objects in JS

I have this code in App.js

const getPlayers = async()=>{
  const players = await API.getPlayers();
  setPlayers(players)
}
getPlayers()

This code in my API.js file

const getPlayers = async () => {
  return getJson(
     fetch(SERVER_URL + 'users', { credentials: 'include'})
  ).then( json => {
    return json.map((user) => {
      return {
        id: user.id,
        name: user.name,
        rank: user.rank
      }
    })
  })
}

This code in my server.js file

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

app.get('/api/players', 
(req, res) => {
  riddleDao.getPlayers()
    .then(async players => {
        res.json(players)
    })
    .catch((err) => res.status(500).json(err));
});

and finally, this in my DataAccessObject.js file

exports.getPlayers = () => {
  return new Promise((resolve, reject) => {
    const sql = 'SELECT * FROM users';
    db.all(sql, [], (err, rows) => {
      if (err) { reject(err); return; }
      else {
        const players = rows.map(row => {
          return {
            id: row.id,
            name: row.name,
            rank: row.rank
          }
        })
        resolve(players);
      }
    });
  });
};

but i am getting this error:

error screenshot

I am expecting to get an array of object in my App.js when i call the getPlayer() function and the objects in the array should have id, name and rank of the players in my db table

>Solution :

I think you’ve got "users" in your fetch URL when it should be "players".

fetch(SERVER_URL + 'users', { credentials: 'include'})

should be

fetch(SERVER_URL + 'players', { credentials: 'include'})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading