Issue
I'm trying to show a barCode for my cardNumber like below:
import "./Home.css";
import React, { useState, useEffect, useRef } from "react";
import axios from "axios";
import { useBarcode } from "react-barcodes";
const Cards: React.FC = () => {
const [cardNumber, setCardNumber] = useState("");
const [content, setContent] = useState("");
//I'm adding a 0 at the beginning of cardNumber, because I need to do so
const cardNumberwithDigits = "" + 0 + cardNumber;
const { inputRef } = useBarcode({
value: cardNumberwithDigits
options: {
background: "#dae2e4",
format: "EAN8",
text: cardNumber,
},
});
//get the cardNumber
useEffect(() => {
axios
.get("/cards/xx")
.then(
(response) => {
setCardNumber(response.data.cardId);
},
(error) => {
const _content =
(error.response && error.response.data) ||
error.message ||
error.toString();
setContent(_content);
}
);
}, []);
return (
<React.Fragment>
<IonPage className="ion-page" id="main-content">
<IonContent className="ion-padding">
<div>
<svg ref={inputRef} />
</div>
</IonContent>
</IonPage>
</React.Fragment>
);
};
export default Cards;
The problem is that cardNumber is initially empty in the first render of Cards.tsx, so I've got the error:
Error: "0" is not a valid input for e
because cardNumber is initially "" and after concatenating with 0, cardNumberwithDigits is "0", which is not a valid value for barCode.
How can I solve the issue and get directly the value of cardNumber, avoiding the cases when it is empty or 0?
Solution
Update:
I found the solution. It seems to be an issue of format.
"0" is an invalid input for format EAN8 but not for format CODE128 , so I will be using a ternary expression for this case.
Every time cardNumberwithDigits !== "0"
use format EAN8
, otherwise use format CODE128
.
format:
cardNumberwithDigits !== "0"
? "EAN8"
: "CODE128",
Answered By - Ani
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.