In order to view the updates in REACTJS, I need to reload the page

Currently, I am engaged in a basic project where I receive user input and store it in a database. Here is the code snippet:

 const [dataFromDB, setDataFromDB] = useState(null);

  const fetchDataFromDB = async () => {
    try {
      const response = await fetch(url);
      const data = await response.json();
      setDataFromDB(data);
      console.log(data);
    } catch (error) {
      console.log(error);
    }
  };

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

  const addTextToDB = async (text) => {
    try {
      await fetch('http://localhost:3001/api/codes', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          text: text,
        }),
      });
    } catch (error) {
      console.error(error);
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    const input = e.target.elements.name.value;
    addTextToDB(input);
    e.target.reset();
    fetchDataFromDB();
    setDataFromDB(dataFromDB);
    console.log(dataFromDB);
  };

  return (
    <div className="App">
      <form onSubmit={handleSubmit}>
        <label>
          Name:
          <input type="text" name="name" />
        </label>
        <input type="submit" value="ADD" />
      </form>
      <div>
        {dataFromDB &&
          dataFromDB.map((item) => <Item key={item._id} name={item.text} />)}
      </div>
    </div>
  );
}

Initially, I fetch the data to display the database content to the user. When a user enters some text and submits by clicking a button, the input will be added to the db. However, to view the changes, I have to refresh the page or enter multiple inputs consecutively.

I am unsure where the issue lies. After submitting the data, I fetch the updated information from the database to reflect the changes made. Subsequently, I update the state using setDataFromDB to visualize the modifications.

Answer №1

When you are working with the handleSubmit function, it's important to note that you are currently making a call to the fetchDataFromDB function and then immediately updating the state of setDataFromDB with the value of dataFromDB. However, this step seems redundant since you are already modifying the state of dataFromDB within the fetchDataFromDB function.

Furthermore, by consecutively calling both addTextToDB and fetchDataFromDB, they could potentially run simultaneously due to their execution speeds and server response times. In some scenarios, it is plausible that fetchDataFromDB may execute and update the state of

dataFromDB</code before <code>addTextToDB
has finished adding new data to the database. To address this issue, it is advisable to ensure that addTextToDB completes entirely and updates the database before initiating fetchDataFromDB to retrieve the most recent information from the server.

const handleSubmit = async (e) => {
  ...
  await addTextToDB(input);
  ...
  await fetchDataFromDB();
}

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

"Unexpected behavior: NextAuth is failing to return defined custom scopes

I am currently working on a NextJS project that utilizes NextAuth. Initially, everything was functioning properly with the default scopes. However, my project now requires additional claims, which are listed in the supported scopes here. "scopes_supporte ...

Guide on how to use Selenium to drag and drop a canvas web element specifically in the Chrome browser

Having trouble moving an image within the canvas web element (avatar editor) on Chrome using Selenium. Check out this canvas element: Watch a quick demo of what I'm trying to accomplish with Selenium Webdriver: Please review the code snippet below. ...

What are the best methods for looping through ids in MongoDB and executing actions on them?

I am working with an entity object that has the following response: [ { "public": false, "_id": "5eb6da3635b1e83", "createdAt": "2020-05-09T16:28:38.493Z", "updatedA ...

Tips for changing the size and color of SVG images in a NextJS application

Looking to customize the color and size of an svg image named "headset.svg". Prior to this, I used next/image: <Image src={'/headset.svg'} alt='logo' width={30} height={30} className='object-contain' /> The s ...

Ways to reset the input field of Material UI

I'm encountering an issue with clearing a form that I created using Material UI. Despite searching for solutions on Stackoverflow, none of them seem to work for me. Using setState did not achieve the desired result of clearing the form. I am looking ...

The functionality of the `next-auth` signOut button click does not seem to accept a variable as input, although

The Nav.jsx component code provided is working as intended. In this implementation, clicking the 'Sign Out' button will redirect the application to http://localhost:3000. 'use client' import { signOut } from 'next-auth/react&apos ...

Personalizing Dialog Title in material-ui

While delving into the world of React and Material-UI, I encountered a challenge in updating the font color in the DialogTitle component. After browsing through various resources, I came across a helpful link that suggested overriding the dialog root class ...

Tips for sorting through mapped information using many selection choices in React

I have generated some sample data and I am looking to display it based on a selection made from a dropdown menu. The content to be displayed should closely match the selection made. For instance, if I choose the option 'java', then the system sh ...

What is the compatible version of Material UI with React 15.5.4?

Currently working on a project in React version 15.5.4 and looking to integrate Material UI into the app. However, I keep encountering an error stating that React version 16.3.0 or higher is required whenever I attempt to install and incorporate Material ...

When using a Redux action type with an optional payload property, TypeScript may raise complaints within the reducer

In my react-ts project, I define the following redux action type: type DataItem = { id: string country: string population: number } type DataAction = { type: string, payload?: DataItem } I included an optional payload property because there are tim ...

What are some tips for troubleshooting server-side issues in a MERN stack application?

Front-end code snippet: define('CreatePage', () => { const auth = useContext(AuthContext) const {request} = useHttp() const [content, setContent] = useState('') const [title, setTitle] = useState('') const [lead, setLead] = ...

How can ExpressJS be used to direct users to individual standalone React applications?

I've spent a lot of time scouring the internet for a solution to my problem, but it seems like maybe I'm not asking in the right way. My project involves creating a Node-Express website where ReactJS is only needed on specific pages, while the r ...

The Recoil Nexus encountered an error: the element type provided is not valid. It should be a string for built-in components or a class/function for composite components, but an object was

Encountered the following error message: Error - Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. at ReactDOMServerRenderer.render ... This issue arose when integra ...

Issue with refreshing a material

When updating a transaction, I am encountering the issue of inadvertently deleting other transactions. My goal is to update only one transaction. Can someone review my backend logic to identify the root cause? Schema Details: const mongoose = require(&apo ...

Remove entry based on time trigger and specific requirement

My project involves an interactive online game. I am in the process of creating a game object that includes various players. My goal is to automatically delete the game data after 3 hours if there are no additional players (besides the creator). I have t ...

React Tabulator - custom header filter for select column - hide 'X' option

Is it possible to remove the 'x' option on header filters in react tabulator columns? The issue arises when users click the 'X' to clear a filter, as expected. However, if they then try to click on the same filter for another list item ...

Unable to fetch data from node API in React application

When making an API call from my React app on port 3000 to a Node API running on port 8080, I encountered an error message: XMLHttpRequest cannot load http://localhost:8080/register. Response to preflight request doesn't pass access control check: No ...

Make sure that the Mongoose save operation is finished before executing the callback function

Encountering a challenge in my initial node app development, where the callback function is triggered before the database write operation is fully completed. The issue arises when an authenticated user visits site.com/model URL. The system checks the data ...

When a user clicks on the datepicker, I want to trigger a change in the

I am working on a Flight API and I need to implement functionality where when the user clicks on the return journey field, the button toggles from single trip to round trip (false to true). <DatePicker hintText="Return Date" errorText={this.state.j ...

Safari iOS does not display any background for Buttons

Encountering an unusual problem with buttons on iOS devices specifically in Safari browser - the background color isn't being applied like it is on Desktop and Android devices. Here are the CSS properties for the button: export const Button = styled.b ...