简体   繁体   中英

React hooks state does not update after deleting

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;
}

});

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;
}

});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM