Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

180
Visualizações
How to render data added with form inputs?

I am rendering information from API, but also I need to render new information added with webform. I made this form to add simple information as the object from the API. How can I render the data added from this form here?

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;

When I add a new book, I need to see it in this document:

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>
    )
}

Can anyone help me? Thanks in advance.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You need to use the concept called lifting the state up here.

Define your state variable books in the common parent component of these two components FormPage and BooksPage

Pass this method to the component FormPage.

const addBook = (book) => {
  setBooks(b => [...b, book])
}

Call this method at

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)          
    })
}

And pass books and setBooks to the page BooksPage.

about 4 years ago · Juan Pablo Isaza Relatório

0

You could move the fetch to a separate function and call again when POST is done

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>
    )
}

And in your form:

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();            
        })
    }
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda