I have been trying to create buy premium option on my website. I was able to successfuly connect with PayPal API and make payments (I can go through the process and it return SUCCESS as status). However when I try to change setState of current user it does not work. I tried to console.log value of premium after setPremium(true) and it would say it's still false...
Here is my code:
import React, { useRef, useEffect, useState } from "react";
import { useHistory } from "react-router-dom";
export default function PayPal() {
const paypal = useRef();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [name, setName] = useState("");
const [phone, setPhone] = useState("");
const [premium, setPremium] = useState();
const history = useHistory();
const info = localStorage.getItem("user-info");
const data = JSON.parse(info);
// console.log(result.premium);
const id = data._id;
async function update() {
let user = password
? {
name,
email,
password,
phone,
premium,
}
: {
name,
email,
phone,
premium,
};
let result = await fetch(`http://localhost:1234/api/users/${id}`, {
method: "PUT",
body: JSON.stringify(user),
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
});
console.log(result);
result = await result.json();
if (result) {
localStorage.removeItem("user-info");
localStorage.setItem("user-info", JSON.stringify(result));
}
// history.push("/profile");
// window.location.reload();
}
useEffect(() => {
function getData() {
setEmail(data.email);
setName(data.name);
setPhone(data.phone);
setPremium(data.premium);
}
getData();
window.paypal
.Buttons({
createOrder: (data, actions, err) => {
return actions.order.create({
intent: "CAPTURE",
purchase_units: [
{
description: `Premium subscription pass`,
amount: { currency_code: "PLN", value: 29.99 },
},
],
});
},
onApprove: async (data, actions) => {
const order = await actions.order.capture();
// console.log(order);
setPremium(true);
// console.log(premium);
update();
// history.push(`/profile`);
// window.location.reload();
},
onError: err => {
console.error(err);
},
})
.render(paypal.current);
(() => setPremium(true))();
}, []);
return (
<div>
<div ref={paypal}></div>
</div>
);
}
Here is also PUT method from my API:
router.put("/:id", async (req, res) => {
const { error } = validateUser(req.body);
if (error)
//400 Bad request
return res.status(400).send(error.details[0].message);
let user = await User.findById(req.params.id);
user.name = req.body.name;
user.email = req.body.email;
user.phone = req.body.phone;
user.premium = req.body.premium;
if (req.body.password) {
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(req.body.password, salt);
}
user = await user.save();
if (!user)
return res.status(404).send(`User with the given ID was not found`);
res.send(user);
});