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

143
Visualizações
Trigger parent API call from child in react

In my parent(Feed) I display a list of posts:

function Feed() {

    const [posts, setPosts] = useState(null);

    useEffect(() => {
        const fetchPosts = async () => {
            try {
                const result = await axios({
                ...
                });
    
                setPosts(result.data);
                ...
            } catch (e) {
                ...
            }
        };
        fetchPosts();
    }, []);

    return (
        ...
            {posts &&
                <div>
                    <PostCompose />                              // post creation
                    {posts.map((item, index) =>                  // map existing posts
                        <Post key={item._id} {...item} />)}      
                </div>
            }
        ...
    )
}

The child(PostCompose) can create a post:

function PostCompose() {

    const [text, setText] = useState('');

    const createPost = async () => {
        try {
            const result = await axios({
                ...
            })
            ...
        } catch (e) {
            ...
        }
    }

    const handleTextChange = (e) => {
        setText(e.target.value);
    }

    return (
        ...
        <textarea onChange={handleTextChange} />
        <button onClick={createPost}>Post</button>
        ...
    )
}

The PostCompose component makes the requests to the backend to create the new posts, but how do I trigger the Feed to refresh to pull the new list of posts?

I feel like my approach might need some work, any help would be great as I'm very new to React. Thanks.

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

0

One way would be to take your fetchPosts function out of the effect callback, using the useCallback hook to memoize it. You can now invoke fetchPosts when the Feed component mounts and provide it to your PostCompose component, as I've done here with the afterPostCreated prop:

function Feed() {
    const [posts, setPosts] = useState(null);

    const fetchPosts = useCallback(async () => {
        try {
            const result = await axios({
                // ...
            });

            setPosts(result.data);
            // ...
        } catch (e) {
            // ...
        }
    }, []);

    useEffect(() => {
        fetchPosts();
    }, [fetchPosts]);

    return (
        posts && (
            <div>
                <PostCompose afterPostCreated={fetchPosts} /> // post creation
                {posts.map(
                    (
                        item,
                        index // map existing posts
                    ) => (
                        <Post key={item._id} {...item} />
                    )
                )}
            </div>
        )
    );
}

Then simply invoke that callback in your PostCompose component, after the post was successfully created:

function PostCompose({ afterPostCreated }) {
    const [text, setText] = useState('');

    const createPost = async () => {
        try {
            const result = await axios({
                // ...
            });
            // ...

            if (afterPostCreated) {
                afterPostCreated();
            }
        } catch (e) {
            // ...
        }
    };

    const handleTextChange = (e) => {
        setText(e.target.value);
    };

    return (
        <>
            <textarea onChange={handleTextChange} />
            <button onClick={createPost}>Post</button>
        </>
    );
}
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