const [computerProtectionPlanState, setComputerProtectionPlanState] = useState([]);
const getProtectionPlansFromDb2 = async (productId) => {
var protectionPlans = "[{" + "p" + productId + ": '";
var URL = variables.API_URL_ADDONS + "/" + productId;
const response = await fetch(URL);
const AddOns = await response.json();
AddOns.forEach(protectionPlan_from_db => {
if (productId == protectionPlan_from_db.productId) {
protectionPlans = protectionPlans + `${ protectionPlan_from_db.add_On }` + ";"
}
});
protectionPlans = protectionPlans + "'}]";
alert(protectionPlans); // See below for the output:
/*
[{p1: 'Acer EI322QUR Sbmiipphx 31.5" 2K WQHD (2560 x 144....;LG 24MQ450-B.AUS 23.8" Full HD (1920 x 1080) 75Hz LE....;HP OMEN 27q 27" 2K QHD (2560 x 1440) 165Hz Gaming....;Brother MFC-J1170DW Wireless Color Inkjet All-in-One....;'}]
*/
setComputerProtectionPlanState(protectionPlans);
}
{(pickupMessageOrProtectionPlans(cart.pickupOnOrOffPic, cart.shipOnOrOffPic, cart.productId) == "Protection Plans") ?
<div>
{computerProtectionPlanState.map((item, index) => (
<div key={index}>{item[["p"] + cart?.productId]?.split(";").map(toDo => (
<div key={toDo}>
<input type="radio" name={["p"] + cart?.productId} value={toDo} onChange={() => changeID(toDo)} />{toDo}
</div>
))}</div>
))}
</div> : ""}
I got the below error message:
Uncaught TypeError: computerProtectionPlanState.map is not a function
at Cart.js:685:1
at Array.map (<anonymous>)
at Cart (Cart.js:621:1)
at renderWithHooks (react-dom.development.js:16340:1)
at updateFunctionComponent (react-dom.development.js:19624:1)
at beginWork (react-dom.development.js:21642:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4196:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4247:1)
at invokeGuardedCallback (react-dom.development.js:4307:1)
at beginWork$1 (react-dom.development.js:27484:1)
If possible, then please give me some code. Thanks a lot in advance!
I am expecting to get a list of radio buttons of computer protection plans. So that the users can choose one of the list of computer protection plans.
Even though you initialized your computerProtectionPlanState
with empty array []
, you set it with string in setComputerProtectionPlanState(protectionPlans);
You cant .map
a string. You need to convert it into JSON at least by parsing it like this setComputerProtectionPlanState(JSON.parse(protectionPlans));
Doing the thing above will at least solve your .map
error but looking at how weird you are constructing and using that data on your display, I assume you’ll have another error after that. You need to read more about proper handling of data thru arrays stuffs.