Home > Software design >  React - Proper syntax for JSON parsing
React - Proper syntax for JSON parsing

Time:12-25

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"
         }
      }
  }
}

CodePudding user response:

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;
  • Related