I am building a like-counter
in a NextJS
ReactJS
app, which stores a persistent incrementable count
value. The max-count
of clicks
/ likes
is to be set to 100
. The button
will not increment the count
any further than this value. The like-counter
value is stored in a FaunaDB.
I can render the value stored in the db
on the front-end, but I can't get the onClick
handler to update the value stored in the db
.
Here is the (commented) code
so far:
Here, State
is declared via a useState
hook.
const [likes, setLikes] = useState([]);
The updateLikes function
async function updateLikes() {
await fetch("/api/newLikes", requestOptionsLikes)
.then(() => getLikes())
.catch((e) => console.log(e))
}
The PUT
method is instantiated:
const requestOptionsLikes = {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ likes })
}
A useEffect hook:
useEffect(() => {
getLikes();
}, []);
The click function:
const handleSubmitLikes = (e) => {
e.preventDefault();
updateLikes();
}
The JSX
that renders the clickable LIKE
button and displays the value from the db
.
<div>
<div onClick={handleSubmitLikes}>LIKE</div>
</div>
{
likes.map((d) => (
<div>
<div>{d.data.like}</div>
</div>
))}
</div>
The code is correctly fetching the likes
from the DB so I think that there is no need to display the getLikes
API
. However the newLikes
API
is returning a 500 Internal Server Error, so I display it below:
const faunadb = require("faunadb");
// your secret hash
const secret = process.env.FAUNADB_SECRET_KEY;
const q = faunadb.query;
const client = new faunadb.Client({ secret });
console.log("CALLLED API")
module.exports = async (req, res) => {
const formData = req.body.data;
console.log("API CALL");
try {
const dbs = await client.query(
console.log("API UPDATE"),
console.log(formData),
q.Update(
q.Ref(q.Collection('Likes'), '305446225474224651'),
{
data: {
like: formData.likes[0].data.like + 1
},
}
)
);
// ok
res.status(200).json(dbs.data);
} catch (e) {
// something went wrong
res.status(500).json({ error: e.message });
}
};
Basically, I can't update the Database via the PUT method.