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

230
Visualizações
Reload page onSubmit in React.js

I want my React.js page to reload after hitting the submit button. This is because I put new entries into my database and once submitting was successful, I want to request new data from the database and display them.

import React, {useEffect, useState} from 'react';
import axios from "axios";

const Questionnaire = () => {
    const [questions, setQuestions] = useState({questions: []});
    const [updated, setUpdated] = useState(false); // approach 1
    // let updated = false // approach 2

    const onSubmit = async (answeredQuestions) => {
        let data = Object.values(answeredQuestions)
        
        axios.put('http://localhost:8000/questionnaire/', data)
            .then(response => {
                // setUpdated(false); // approach 1
                // updated = !updated; // approach 2
            }
        );
    };

    useEffect( () => {
        axios.get('http://localhost:8000/questionnaire/', {})
            .then((response) => {
                setQuestions({"questions": response.data});
                setUpdated(true); // approach 1
            });
    }, [updated]);

    return (
        <> 
            <Questions questions={questions} onSubmit={onSubmit} />
        </>
    );
}

export default Questionnaire;

I want the useEffect() to be executed immediately after getting the response from axios.put() so that the new questions can be requested and displayed to the user. I tried out two approaches, but either axios.get() was executed twice or the re-render didn't work properly.

I appreciate your support!

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

0

Updated answer.

It seems that your logic for approach 1 is not completely correct. Try this instead

import React, {useEffect, useState} from 'react';
import axios from "axios";

const Questionnaire = () => {
    const [questions, setQuestions] = useState({questions: []});
    const [updated, setUpdated] = useState(true); // Set to true to trigger get on first render

    const onSubmit = async (answeredQuestions) => {
        let data = Object.values(answeredQuestions)
        
        axios.put('http://localhost:8000/questionnaire/', data)
            .then(response => {
                setUpdated(true); // approach 1
            }
        );
    };

    useEffect( () => {
        if (updated) {
            axios.get('http://localhost:8000/questionnaire/', {})
                .then((response) => {
                    setQuestions({"questions": response.data});
                    setUpdated(false); // approach 1
                });
        }
    }, [updated]);

    return (
        <> 
            <Questions questions={questions} onSubmit={onSubmit} />
        </>
    );
}

export default Questionnaire;

Old answer:

Is there any reason why you need to get data in a useEffect? Or could you simply do the get-request whenever the put is resolved?

import React, {useEffect, useState} from 'react';
import axios from "axios";

const Questionnaire = () => {
    const [questions, setQuestions] = useState({questions: []});

    const onSubmit = async (answeredQuestions) => {
        let data = Object.values(answeredQuestions)
        
        axios.put('http://localhost:8000/questionnaire/', data)
            .then(response => {
                axios.get('http://localhost:8000/questionnaire/', {})
                    .then((response) => {
                        setQuestions({"questions": response.data});
                    });
            }
        );
    };

    return (
        <> 
            <Questions questions={questions} onSubmit={onSubmit} />
        </>
    );
}

export default Questionnaire;

(Or do it with async/await since you are declaring onSubmit to be an async function)

about 4 years ago · Juan Pablo Isaza Relatório

0

Use location.reload(); after put/post request is finished as below

import React, {useEffect, useState} from 'react';
import axios from "axios";

const Questionnaire = () => {
    const [questions, setQuestions] = useState({questions: []});
    const [updated, setUpdated] = useState(false); // approach 1
    // let updated = false // approach 2

    const onSubmit = async (answeredQuestions) => {
        let data = Object.values(answeredQuestions)
        
        axios.put('http://localhost:8000/questionnaire/', data)
            .then(response => {
                //The below line will force browser refresh
                location.reload();
            }
        );
    };
....
//the rest of the codes
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