Home > Net >  Mapping data form database to an array of objects in JS
Mapping data form database to an array of objects in JS

Time:07-13

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

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

CodePudding user response:

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'})

CodePudding user response:

your api endpoint differs from the url you are sending requests

app.get('/api/players', 

you are listening to "players" but

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

you are fetching "users"

  • Related