Estoy representando información de la API, pero también necesito representar nueva información agregada con el formulario web. Hice este formulario para agregar información simple como el objeto de la API. ¿Cómo puedo representar aquí los datos agregados desde este formulario?
function FormPage({ setData }) { const [name, setName] = useState(''); const [description, setDescription] = useState(''); const [id, setId] = useState(0); const handleSubmit = (e) => { e.preventDefault(); const book= { name, description, id} fetch('link-from-api', { method: 'POST', headers: { "Content-Type": "application/json" }, body: JSON.stringify(book) }).then(() => { console.log('new book added'); }) } return ( <> <form noValidate autoComplete="off" onSubmit={handleSubmit}> <TextField required value={name} onChange={(e) => setName(e.target.value)} label="Name" /> <TextField required value={description} onChange={(e) => setDescription(e.target.value)} label="Description" /> <button type="submit" onClick={handleId}> set</button> </form> </> ); } export default FormPage;Cuando agrego un nuevo libro, necesito verlo en este documento:
function BooksPage() { const [books, setBooks] = useState([]); useEffect(() => { fetch('link here') .then(res => { return res.json(); }) .then((data) => { setBooks(data) }) }, []) return ( <Container> <Header /> {books && <ListBooks props={books} />} </Container> ) }¿Alguien puede ayudarme? Gracias por adelantado.
Necesitas usar el concepto llamado lifting the state up aquí.
Defina sus books de variables de estado en el componente principal común de estos dos componentes FormPage y BooksPage
Pase este método al componente FormPage.
const addBook = (book) => { setBooks(b => [...b, book]) }Llame a este método en
const handleSubmit = (e) => { e.preventDefault(); const book= { name, description, id} fetch('link-from-api', { method: 'POST', headers: { "Content-Type": "application/json" }, body: JSON.stringify(book) }).then(() => { console.log('new book added'); addBook(book) }) } Y pase books y setBooks a la página BooksPage.
Puede mover la búsqueda a una función separada y volver a llamar cuando finalice POST
function BooksPage() { const [books, setBooks] = useState([]); function fetchBooks() { fetch('link here') .then(res => { return res.json(); }) .then((data) => { setBooks(data) }) } useEffect(() => { fetchBooks(); }, []) return ( <Container> <Header /> {books && <ListBooks props={books} />} <FormPage fetchBooks={fetchBooks} /> </Container> ) }Y en tu forma:
const handleSubmit = (e) => { e.preventDefault(); const book= { name, description, id} fetch('link-from-api', { method: 'POST', headers: { "Content-Type": "application/json" }, body: JSON.stringify(book) }).then(() => { console.log('new book added'); // fetch again fetchBooks(); }) }