As a beginner to React JS, I keep getting TypeErrors when I run my App.js. Could you please advise me what I can do to resolve this issue?
I am now working on the frontend of a program that allows customers to pre-order food and beverages online.
import React, { useState, useEffect } from "react";
import axios from "axios";
function App() {
const [items, setItems] = useState([]);
const [cart, setCart] = useState([]);
useEffect(() => {
axios.get("/api/items").then((response) => setItems(response.data));
}, []);
const addToCart = (item) => {
setCart([...cart, item]);
};
const removeFromCart = (item) => {
setCart(cart.filter((i) => i.id !== item.id));
};
const submitOrder = () => {
const order = {
customer: {
firstName: "",
lastName: "",
email: "",
phoneNumber: "",
},
items: cart,
paymentMethod: "CASH",
};
axios.post("/api/orders", order).then(() => setCart([]));
};
return (
<div>
<h1>Food and Beverage Items</h1>
<ul>
{items.map((item) => (
<li key={item.id}>
{item.name} ({item.price}){" "}
<button onClick={() => addToCart(item)}>Add to Cart</button>
</li>
))}
</ul>
<h1>Cart</h1>
<ul>
{cart.map((item) => (
<li key={item.id}>
{item.name} ({item.price}){" "}
<button onClick={() => removeFromCart(item)}>Remove</button>
</li>
))}
</ul>
<button onClick={submitOrder}>Submit Order</button>
</div>
)}
export default App;
2
Answers
All seems to be correct, except for a missing closing parenthesis at the end of the component definition.
I added a closing parenthesis at the end of the component definition to match the opening parenthesis at the beginning. Now the code should work fine without any syntax errors.
Put the ul in the map and the index could come from the map methode itself. Try this maybe :