const Cart = () => { const cart = useAppSelector((state) => state.cart); const…
- User
const Cart = () => { const cart = useAppSelector((state) => state.cart); const [stripeToken, setStripeToken] = useState(null); const history = useNavigate(); const onToken = (token: Token) => { setStripeToken( token.id); }; useEffect(() => { const makeRequest = async () => { try { const res = await userRequest.post("/checkout/payment", { tokenId: stripeToken.id, amount: 100, });
history("/success", { state: { data: res.data } }); } catch (err) { console.log("it gives this error " + err); } }; stripeToken && makeRequest();}, [stripeToken, cart.total, history]);
Argument of type 'string' is not assignable to parameter of type 'SetStateAction'. 'stripeToken' is possibly 'null'.ts(18047)
- Assistant
This error is occurring because the initial value of
stripeTokenisnull, and it is possible that thestripeTokenstate variable is still null when themakeRequestfunction is called.To fix this issue, you should add a null check to ensure that
stripeTokenhas a value before accessing its properties. One way to do this is to modify themakeRequestfunction as follows:const makeRequest = async () => { if (stripeToken) { try { const res = await userRequest.post("/checkout/payment", { tokenId: stripeToken, amount: cart.total * 100, }); history("/success", { state: { data: res.data } }); } catch (err) { console.log("it gives this error " + err); } } };In this modified version of
makeRequest, we check ifstripeTokenis truthy before making the API call. IfstripeTokenis null or undefined, the function will exit early without making the API call.Note that we also changed
stripeToken.idto juststripeTokenin the field of the API call. This is because the variable already contains the token ID as a string, so we don't need to access it through the property. Additionally, we changed the field to use the value instead of hardcoding . - User
but srtipeToken.id cannot be null?
- Assistant
You are correct that the
tokenIdfield should not benull, sincetoken.idshould always be defined when a token is received from Stripe. So it's possible that the issue is with thesetStripeTokenfunction.To fix this issue, you should modify the
setStripeTokenfunction to always receive a defined value. One way to do this is to modify the code as follows:const onToken = (token: Token) => { if (token && token.id) { setStripeToken(token.id); } };In this modified version of
onToken, we check iftokenexists and has anidvalue before setting thestripeTokenstate variable. Iftokenisnullorundefined, or iftoken.idisnullorundefined, thesetStripeTokenfunction will not be called.This should prevent
stripeTokenfrom beingnulland should allow themakeRequestfunction to make the API call without errors.