'Only one post updates in React, when I do another post it does not shows
When I post an item it shows up right away. But when I post another i have to update the page to see it. I think i have to put a res.json() somewhere in my backend to make it work.
Here's my backend code:
router.post("/new", async (req, res, next) => {
const {
title,
description,
imageUrl,
genre,
releaseYear
} = req.body;
const game = {
title,
description,
imageUrl,
genre,
urlSlug: generateUrlSlug(title),
releaseYear,
};
const db = req.app.locals.db;
if(!game) {
// res.status(400).send();
}
else {
await saveGame(game, db);
res.json(game)
}
});
async function saveGame(game, db, res) {
const sql = `
INSERT INTO game (
title,
description,
imageurl,
genre,
urlslug,
releaseyear
) VALUES ($1, $2, $3, $4, $5, $6)
`;
await db.query(sql, [
game.title,
game.description,
game.imageUrl,
game.genre,
game.urlSlug,
game.releaseYear
]);
}
and frontend
const [games, setGames] = useState([]);
useEffect(() => {
getGames();
}, [])
const getGames = () => {
fetch('http://localhost:5000/api/admin/games')
.then((result) => {
result.json().then((resp) => {
setGames(resp)
})
})
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
