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!