ba23-python / UpgradeHub-React-Weekly-Meal-Planner

Project assignment to share for evaluation
1 stars 0 forks source link

Add 1 new menu with POST https://664c9e9635bbda10988127e7.mockapi.io/comida #12

Closed ba23-python closed 5 months ago

ba23-python commented 5 months ago

{ "nombre": "Ensalada de aguacate y canonigos", "categoria": "Cena", "descripcion": "Ensalada de tomate, aguacate y canonigos alineada con virgen extra y limon", "id": "22" }

Create a function to make a POST request: This function will send the new item data to the mock API. Set up form handling: Create input fields and manage their state to gather new item details. Integrate the POST request function: Call the addNewItem function upon form submission and update the state to reflect the new item in the UI.

Opcion 1 para Fetch POST con axios

import axios from 'axios';

const addNewItem = async (newItem) => { const response = await axios.post('https://mockapi.io/projects/664c9e9635bbda10988127e8/comida', newItem); return response.data; };

Opcion 2 sin axios

const addNewItem = async (newItem) => { const response = await fetch('https://mockapi.io/projects/664c9e9635bbda10988127e8/comida', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(newItem), });

if (!response.ok) { throw new Error('Failed to add new item'); }

return await response.json(); };


Update Your App Component

import React, { useState } from 'react';

const App = () => { const [menu, setMenu] = useState([]); const [newItem, setNewItem] = useState({ nombre: '', categoria: '', descripcion: '', dia: '', });

const handleInputChange = (e) => { const { name, value } = e.target; setNewItem((prevItem) => ({ ...prevItem,

}));

};

const handleAddNewItem = async (e) => { e.preventDefault();

try {
  const addedItem = await addNewItem({ ...newItem, id: String(menu.length + 1) });
  setMenu((prevMenu) => [...prevMenu, addedItem]);
} catch (error) {
  console.error('Error adding new item:', error);
}

};

return (

Meal Plan

    {menu.map(meal => (
  • {meal.nombre} - {meal.categoria} ({meal.dia})
  • ))}

); };

export default App;