Home > OS >  React hooks state does not update after deleting
React hooks state does not update after deleting

Time:05-19

So my state does not update immediatly after deleting an item. I have tried to filter games inside of onDelete. Like setGames(games.filter(game => game.urlSlug !== urlSlug)) but with no success.Does anyone have any ideas? :)

const [games, setGames] = useState([]);

useEffect(() => {
  getGames();
}, [])

const getGames = async () => {
  await fetch('http://localhost:5000/api/admin/games')
  .then((result) => {
    result.json().then((resp) => {
      setGames(resp)
    })
  })
}

const onDelete = async (urlSlug) => {
  await fetch(`http://localhost:5000/api/admin/games/${urlSlug}`, {
    method: 'DELETE'
  }).then((res) => {
    res.json().then((data) => {
     getGames();
    })
  })

[][1]

This is my backend in node.js

router.delete("/games/:urlslug", async (req, res, next) => {

const {urlslug} = req.params;
const db = req.app.locals.db;

try {

const sql = `
DELETE FROM game WHERE urlslug = $1
`;

await db.query(sql, [urlslug])
// res.status(404).send();
return true;

}
catch(error) {
  console.error(error);
  return false;
}

});

CodePudding user response:

Thanks for much VladSofronov! It was my backend that was wrong. I fixed it :)

router.delete("/games/:urlslug", async (req, res, next) => {

const {urlslug} = req.params;
const db = req.app.locals.db;

try {

const sql = `
DELETE FROM game WHERE urlslug = $1
`;

await db.query(sql, [urlslug])
res.status(204).send();
res.json(urlslug)
return true;

}
catch(error) {
  console.error(error);
  return false;
}

});

CodePudding user response:

Are you sure that your API gets updated after you hit it up? If you console.log(data) before getGames() does it return without the element you are trying to remove?

As for filtering the state the correct way would probably be something like setGames(prevGames => prevGames.filter(game => game.urlSlug !== urlSlug)}

  • Related