Revitalize website when submitting in React.js

I need assistance with reloading my React.js page after clicking the submit button. The purpose of this is to update the displayed data by fetching new entries from the database.

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

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

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

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

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

export default Questionnaire;

I want the useEffect() function to run immediately after receiving a response from the axios.put() request in order to fetch and display new questions to the user. I attempted two different methods, but they resulted in either duplicate executions of axios.get() or improper rendering.

Your help would be greatly appreciated!

Answer №1

Utilize the location.reload(); method after completing a put/post request in the following manner:

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

const QuestionnaireComponent = () => {
    const [questionList, setQuestionList] = useState({questions: []});
    const [updatesMade, setUpdatesMade] = useState(false); // Option 1
    // let updatesMade = false // Option 2

    const onSubmission = async (answeredQuestions) => {
        let data = Object.values(answeredQuestions)
        
        axios.put('http://localhost:8000/questionnaire/', data)
            .then(response => {
                // The line below will forcefully refresh the browser
                location.reload();
            }
        );
    };
....
// Additional code goes here

Answer №2

Updated response.

Your approach 1 logic for this situation seems to have some flaws. Consider using the following revised solution instead:

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

const Questionnaire = () => {
    const [questions, setQuestions] = useState({questions: []});
    const [updated, setUpdated] = useState(true); // Maintain state of update status

    const submitForm = async (answeredQuestions) => {
        let data = Object.values(answeredQuestions)
        
        axios.put('http://localhost:8000/questionnaire/', data)
            .then(response => {
                setUpdated(true); // Trigger update on form submission
            }
        );
    };

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

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

export default Questionnaire;

Prior response:

Is there any specific reason for utilizing a useEffect function in order to retrieve data? Alternatively, you could directly make the GET request once the PUT operation is resolved.

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

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

    const submitForm = 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={submitForm} />
        </>
    );
}

export default Questionnaire;

(Alternatively, you could use async/await since the onSubmit function is defined as an asynchronous function)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging the power of useEffect in Next.js to interact with the window object

I encountered an issue when trying to access window.localStorage in my Next.js application. Since Next.js allows for both server-side and client-side rendering, I ran into an error when attempting to set the default value of a state using local storage lik ...

Refresh the react-table when an event occurs

I'm utilizing React and the react-table framework to display and list my data respectively. One issue I am facing is that after creating a new object in my database, I have trouble refreshing the table without navigating away from the view. My query ...

My date function in Node JS is throwing an error, can someone please help me troubleshoot?

I encountered an error with new date(); while working with node js and express npm plugin. I built a variable date but faced some compilation errors. This is my code .js var update_time = new Date(); update_time.formatDate("y/m/d"); When I run ...

Utilize jQuery and JavaScript dynamically in an HTML document on iOS devices

Having some trouble with this code snippet and getting it to work as intended. - (void)viewDidLoad { [super viewDidLoad]; _webview.delegate = self; [_webview loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBun ...

Unable to retrieve data due to a network error: NetworkError occurred while trying to access the resource

I have been working with the graph.cool API in conjunction with React and Apollo. While developing an authentication system using graph.cool's default email pass integration, I encountered an issue where the login mutation worked perfectly fine, but t ...

Seamlessly Loading Comments onto the Page without Any Need for Refresh

I am new to JavaScript and I am trying to understand how to add comments to posts dynamically without needing to refresh the page. So far, I have been successful in implementing a Like button using JS by following online tutorials. However, I need some gui ...

Ways to dynamically include onClick on a div in a react component based on certain conditions

Is it possible to conditionally set the onClick event on a div element in React based on the value of a property called canClick? Instead of directly checking this.state in the event handler, I am hoping to find a way to implement this logic within the re ...

There was a failure to retrieve any data when trying to send an ajax request to

When attempting to send JSON data to my PHP, I am not receiving any response when accessing it in my PHP code. Below is the Ajax request being made: var project = {project:"A"}; var dataPost = JSON.stringify(project); $.ajax({ url: 'fetchDate.p ...

Storing the output of asynchronous promises in an array using async/await technique

I am currently working on a script to tally elements in a JSON file. However, I am encountering difficulty in saving the results of promises into an array. Below is the async function responsible for counting the elements: async function countItems(direct ...

Having trouble with NextJs router 404 error when refreshing the page on Digital Ocean?

I am currently working with a NextJs project that has been exported as a static site and is being hosted on Digital Ocean's App platform. I am using next/router to handle routing within the application. One issue that I have encountered is when attem ...

React hooks allow components to function properly even if the setState function is not explicitly called

Check out my React hooks code below: function State(){ var [msg,set_msg]=React.useState("hello") //not rendered, just to force render var [data,set_data]=React.useState({version:1}) function onClick(){ set_msg(x=>x+'x') //just to force ...

Display various v-dialog boxes with distinct contents in a vue.js environment

Hello there! I am currently working on customizing a Vue.js template and I have encountered an issue with displaying dynamic v-dialogs using a looping statement. Currently, the dialog shows all at once instead of individually. Here is the structure of my ...

How should I manage objects that are passed by reference in the context of functional programming?

Lately, I have been experimenting with some code in an attempt to delve deeper into functional programming. However, I seem to have hit a snag. I am struggling with handling an object. My goal is to add key-value pairs to an object without reassigning it, ...

The button event is currently only targeting the initial class. (Jquery)

I am having an issue where only the first instance of the saveBtn class is being saved into local storage when clicked. Can anyone provide some assistance with this? Here is the HTML: <div class="hour-container" id="8am"> & ...

Determine the total cost based on the quantity purchased

I created a webpage for employees to select an item from a dropdown menu, and it will automatically display the price of that item. Check out my code below: <script> $(document).ready(function() { $('#price_input').on('change' ...

Struggling to properly render JSON data

Having trouble accessing specific elements in a script that merges local JSON files using AJAX? The script works fine in Chrome Console, but you can't reach certain elements like 'object.country'. Any suggestions on how to tackle this issue? ...

What is the process for transforming an asynchronous method into a synchronous version?

I am currently working on creating a functionality similar to the core fs module's methods, where there is an Async method by default and a Sync method if requested like fs.readDir() and fs.readDirSync(). In my case, I have a method named fetchUrls w ...

Implementing asynchronous loading of an image onto a webpage using JavaScript

Is it possible to asynchronously load an image specified in the src attribute of an HTML image tag? I am trying to invoke a Java class using an image src tag, but I want this to happen asynchronously without affecting the current functionality of the web ...

How can we detect line breaks within a selection using JavaScript?

Apologies for the lack of expertise in the content below, as it is being produced by a designer experimenting with coding :D The goal here is to determine the number of lines selected or highlighted by the cursor. When I mention "lines," I mean what is vi ...

How can I determine if a URL in react js includes a specific string?

I am working on a project where I need to check if a given URL contains the string youtube using react hooks in React JS. This is what my current code looks like: useEffect(() => { let srcLink = "www.google.com/https://img.youtube.com/vi/h9-qcy3HQn ...