0

I am pulling in transaction details from const details and I need to pull out brand from the JSON paymentResponse. I am receiving an undefined error but everything in let cardType looks correct. What am I missing?

let cardType = JSON.parse(orderDetails.paymentResponse).data?.payment_method_details?.card?.brand;

The code:

 const [orderDetails, setOrderDetails] = useState({});
  
  const getOrderDetails = async () => {
    let data = {};
    data.orderId = params.id;
    const details = await orderApi.getOrderDetails(userAuthToken, data);
    if (details && details.data.success) {
      if (details.data.data.length > 0) {
        setOrderDetails(details.data.data[0]);
      } else {
        navigate('/');
      }
    } else {
      navigate('/');
    }
  };

  useEffect(() => {
    (async () => {
      if (params.id) {
        setLoading(true);
        await getOrderDetails();
        setLoading(false);
      } else {
        navigate('/');
      }
    })();
  }, [params.id]);
  //
  let cardType = JSON.parse(orderDetails.paymentResponse).data?.payment_method_details?.card?.brand;

  console.log(cardType);

enter image description here

The JSON structure where brand is:

{
   "data":{
      "payment_method_details":{
         "card":{
            "brand":"jcb"
         }
      }
  }
}
2
  • Cam you share the full orderDetails and error message? Commented Dec 24, 2022 at 21:47
  • if (orderDetails) let cardType = JSON.parse(orderDetails.paymentResponse... Cause your orderDetails is not avaiable once your component loads... Commented Dec 24, 2022 at 21:52

1 Answer 1

1

Since your orderDetails object is empty when your component first loads, the orderDetails.paymentResponse is undefined, and trying to access its data property is throwing the error. You'd need to handle this undefined variable because JSON.parse cannot do that for you. Since you're already using the optional chaining operator, changing that particular line as follows should get rid of the error:

  let cardType = JSON.parse(orderDetails?.paymentResponse || "{}")?.data?.payment_method_details?.card?.brand;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.