What is the process of synchronizing state in react.js?

I am struggling to update the state and component in my code. When I press a button and change the value of one of the props in the popup component, the prop value does not get updated. I suspect this issue is due to using setState. I researched a possible solution using the useEffect hook, but I'm having trouble implementing it. Here's the code snippet:

My objective is to transition from the form with Data0 prop to have a Data1 prop, however, the prop doesn't seem to update at all. I'm trying to simulate multiple clicks on objects, resulting in an update in the formData value. The parent component is app.js and the child component is the popup, which should display "Bob" and a specific date rather than just the original name and date strings.

import React, { useState, useEffect } from 'react';
import './App.css';
import FormDialog from './component/popup'
import Button from '@material-ui/core/Button';


function App() {
  const Data0 = { name:'original name', date:'original date' }
  const Data1 = { name:'Bob', date:'1939' }
  const [formStatus, setFormStatus] = React.useState(false);
  const [formData2, setFormData2] = useState(Data0)
  const [tempForm, setTempForm] = useState(<FormDialog formStatus={formStatus} handelForm={() => handleForm()} Data0={Data0}/>)


  const handleForm = () => {
    const tempForm = <FormDialog formStatus={formStatus} handelForm={() => handleForm()} Data0={Data1}/>
    setTempForm(tempForm);
  };

  useEffect(() => {
    const tempForm = <FormDialog formStatus={formStatus} handelForm={() => handleForm()} Data0={Data1}/>
    setTempForm(tempForm);
    setFormStatus(!formStatus);
    console.log('formData2 EFFECT', formData2)
    setTempForm(tempForm);
    setFormStatus(!formStatus);
    setFormStatus(!formStatus);
  }, [formData2]
  );

  return (
    <div className="App">
      <h1 align="center">React-App</h1>
      <h4 align='center'>Render Custom Component in Material Table</h4>
      <Button variant="outlined" color="primary" onClick={() => handleForm()}>
        Vendor row
      </Button>
      {tempForm}
      {formData2.billingVendor}
    </div>
  );
}

export default App;
export default function FormDialog (props) {
  let [Data, setData] = React.useState(props.Data0);

  return (
    <React.Fragment>
      <Dialog
        maxWidth='lg'
        open={props.formStatus}
        aria-labelledby="max-width-dialog-title"
        disableBackdropClick={true}
        disableEscapeKeyDown={true}
      >
        <DialogTitle className={classes.title}>{Data.name}</DialogTitle>
        <Divider />
        <DialogContent>
            <DialogContentText>
                Please be cautious when updating the fields below.
            </DialogContentText>
            <form noValidate>
                <FormControl className={classes.formControl} fullWidth={true}>
                <div className={classes.root}>
                    <TextField
                        fullWidth
                        label='Date'
                        style={{ margin: 8 }}
                        disabled
                        value={Data.name}
                        variant="outlined"
                        />
                    <br/>
                    <TextField
                        fullWidth
                        label='Date'
                        style={{ margin: 8 }}
                        disabled
                        value={Data.name}
                        variant="outlined"
                        />
                    <br/>
                    <TextField
                        fullWidth
                        style={{ margin: 8 }}
                        disabled
                        value={Data.date}
                        variant="outlined"
                        />
                    <br/>
                    <TextField
                        fullWidth
                        style={{ margin: 8 }}
                        disabled
                        value={Data.date}
                        variant="outlined"
                        />
                    <br/>
                    
                    </div>

                </FormControl>
            </form>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => props.handleForm()} color="primary">
            Close
          </Button>
        </DialogActions>
      </Dialog>
    </React.Fragment>
  );
}

Answer №1

Your current approach to storing a react component in the state is not recommended. It's better to dynamically load the component or pass the necessary prop instead.

import React, { useState, useEffect } from 'react';
import './App.css';
import FormDialog from './component/popup'
import Button from '@material-ui/core/Button';


function App() {
  const Data0 = { name:'original name', date:'original date' }
  const Data1 = { name:'Bob', date:'1939' }
  const [formStatus, setformStatus] = React.useState(false);
  const [formdata2, setformData2] = useState(Data0)
  const [formData, setFormData] = useState(Data0)


  const handelForm = () => {
    // update the state as needed
    setFormData(Data0);
  };

  return (
    <div className="App">
      <h1 align="center">React-App</h1>
      <h4 align='center'>Render Custom Component in Material Table</h4>
      <Button variant="outlined" color="primary" onClick={() => handelForm()}>
        Vendor row
      </Button>
       <FormDialog formStatus = {formStatus} handelForm={() => handelForm()} Data0={formData}/>
    </div>
  );
}

export default App;

Add a useEffect hook in the FormDialog component to handle changes:

useEffect(() => {
    setData(props.Data0)
}, [props.Data0])

This will update the state with any changes made.

Answer №2

You are establishing a fresh state based on the props in your child component, which operates separately from the parent component's state. Consequently, modifications made in the child component do not affect the parent component.

To rectify this issue,

  1. Begin by creating the state within your parent component:
const [Data0, setData0] = useState({ name:'original name', date:'original date' })
  1. Next, pass the setState function to enable changing the value within the parent component from your children:
const tempform = <FormDialog formStatus = {formStatus} handelForm={() => handelForm()} Data={Data1} setData={setData0}/>
  1. Adjust the value within your child component as needed:
let {Data, setData} = props;

Subsequently, when calling setData, you should be invoking the one located in your parent component, allowing for seamless updates to the value.

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

What is the process for incorporating a Bootstrap link into a specific ReactJS file?

In my current project using React JS, I found the need to incorporate Bootstrap in certain pages. To do this, I initially placed the following code snippet in the Public folder within index.html: <link rel="stylesheet" href="https://netdna.bootstrapc ...

Is it possible to retrieve the current CSS value set by a media query using JavaScript?

Currently working on a website project that involves accessing and manipulating the display property of a menu. The goal is to toggle the menu open or closed based on its current state. In my setup, the initial state of the menu is defined as closed using ...

Is it possible for me to generate c3js graphs dynamically?

Here is my current progress: <div id="chart"></div> <script> var names = <?php echo json_encode($array1) ?>; var count = <?php echo json_encode($array2) ?>; var x=0; while (names[x]!=null) ...

How can I easily implement basic password protection on a straightforward Next.js web app hosted on Vercel?

Adding a simple password validation step to a dashboard that only a select few would access. The data is not highly sensitive, but some basic protection is desired to limit unauthorized access. While not expecting targeted attacks from hackers, the goal is ...

How to use jQuery to retrieve the style of an element based on a specific data attribute

I've been using bxSlider and I decided to create a unique custom pager using the pagerCustom option. My goal was to make the pager resemble a thumbnail pager, so I attempted to copy the style of each slide and attach it to the corresponding pager. For ...

Alter the navigation background when moving between sections on a one-page website

I need to ensure that the background of the navigation remains transparent on the "home" section. However, when switching to other sections, the background color of the navigation becomes permanently black. <header class="clearfix"> <nav> ...

Utilize the jQuery autocomplete UI Widget to trigger a select event on a dynamically generated row in a table

Currently, I have successfully implemented a jQuery autocomplete feature on the text input of a table data element called txtRow1. The data for this autocomplete is fetched remotely from a MySQL database and returned in JSON format as 'value' for ...

The date conversion within AngularJS's interpolation is resulting in an incorrect timestamp

Given a timestamp of 1519347000, I am trying to convert it into a date format using interpolation like so: {{$ctrl.myTimestamp | date:'MMM d y, hh:mm'}} The resulting value is Jan 18 1970, 04:02, which is incorrect. The correct date should be F ...

How does the question mark symbol (?) behave when utilizing it in response? Specifically in relation to data, the API, and the fetch API

Have you encountered the curious sequence of symbols in this context? data?.name Could you explain the significance of the question mark (?) between 'data' and the period? ...

How can I design a form that resembles the sign-in form used by Google?

Currently, I am in the process of creating a contact form for a website that is inspired by the design of Google's material sign-in form. I have successfully implemented an effect where clicking on the input field causes the label to change its posit ...

Using curly braces when invoking a function from HTML within a Vue.js application

When I call a function, for example on click, it works whether or not I use curly braces. However, I have created a function that triggers a custom event from a child component. I then await this event in a parent component and update the state with my par ...

Open webview link in default browser when the link target is set to "_blank" in React Native

I'm working with a WebView that has multiple links inside. If one of those links is selected and it includes a target="_blank" attribute, how can I make it open in the default browser? <WebView ref={webViewRef} source={{ uri: ' ...

What is the best approach for creating a test case for a bootstrap-vue modal component

Exploring ways to effectively test the bootstrap vue modal display function. On the project page, the modal toggles its visibility using the toggleModal method triggered by a button click. The modal's display style is switched between 'none' ...

Leveraging JavaScript to create a horizontal divider

Just a quick question - how can I create a horizontal line in Javascript that has the same customization options as the HTML <hr> tag? I need to be able to specify the color and thickness of the line. I am working on a website where I have to includ ...

Generate a table framework by dynamically adjusting the number of rows and columns

I'm running into an issue with my implementation of nested for-loops to dynamically generate a table using JavaScript. For this particular scenario, let's assume numRows = 2 and numCols = 6. This is the code snippet in question: let table = $( ...

running a prompt command from my PHP/HTML script

I currently run a puppeteer program by typing c:\myProgram>node index.js in the command prompt. However, I would like to automate this process through my PHP program instead of manually entering it each time. Something similar to this pseudo-code ...

Transferring JSON data using DWR (Direct Web Remoting)

Utilizing DWR for AJAX calls in my project involves the conversion of JavaScript objects to Java objects by analyzing the Java class. My goal is to send and receive a JSON-like structure through DWR. For example: JavaScript Object: { "name" : "TamilVe ...

Sort the inner array within an outer array

const dataArray = [ { id: 1, title: "stuffed chicken is tasty as anything", picture: "./img/chicken.jpg", tags: ["oooo", "tasty", "stuffed"] }, { id: 2, title: "noodles with shrimp and salad", ...

Combine two objects and discard any duplicate keys

I have two objects named original and custom. My goal is to merge the content from custom into original, but only update the keys in original that are also present in the custom object. Here is an example scenario: var original = { coupon: { ...

What is the best way to retrieve user input from a form within an Ajax.ActionLink?

My webpage is designed to be simple, featuring a picture and a comment section that functions as a partial view. I am looking to only refresh the partial view when a new comment is submitted. Here's what I have coded: <tr> & ...