You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
importReact,{useEffect,useState}from'react';importapifrom"../api.js";importAddFruitFormfrom'./AddFruitForm';constFruitList=()=>{const[fruits,setFruits]=useState([]);constfetchFruits=async()=>{try{constresponse=awaitapi.get('/fruits');setFruits(response.data.fruits);}catch(error){console.error("Error fetching fruits",error);}};constaddFruit=async(fruitName)=>{try{awaitapi.post('/fruits',{name: fruitName});fetchFruits();// Refresh the list after adding a fruit}catch(error){console.error("Error adding fruit",error);}};useEffect(()=>{fetchFruits();},[]);return(<div><h2>Fruits List</h2><ul>{fruits.map((fruit,index)=>(<likey={index}>{fruit.name}</li>))}</ul><AddFruitFormaddFruit={addFruit}/></div>);};exportdefaultFruitList;
AddFruitForm.jsx
importReact,{useState}from'react';constAddFruitForm=({ addFruit })=>{const[fruitName,setFruitName]=useState('');consthandleSubmit=(event)=>{event.preventDefault();if(fruitName){addFruit(fruitName);setFruitName('');}};return(<formonSubmit={handleSubmit}><inputtype="text"value={fruitName}onChange={(e)=>setFruitName(e.target.value)}placeholder="Enter fruit name"/><buttontype="submit">Add Fruit</button></form>);};exportdefaultAddFruitForm;
importaxiosfrom'axios';// Create an instance of axios with the base URLconstapi=axios.create({baseURL: "http://localhost:8000"});// Export the Axios instanceexportdefaultapi;