0

I have multiple components already created that are on the same level which makes it hard for me to pass data between them. The HealthForm component has an input field which takes a host url and then fetches to APIs when a button is click. All of that works well. What I need is to pass that url to all the other components (ProductForm, xForm, yForm, zForm...) What I have now is that my backend server saves the url but that creates implications whee multiple browsers are using the webpage.

What I'm thinking that needs to be changed is to make the HealthForm the parent component of the other Forms. However, my App.js looks like this which has only the routes in it. A separate HeaderTabs links to the right routes...

EDIT The code now successfully saves and passes the url to its child components. The issue is that the page re-renders when i update the parent state in HealthForm.

class App extends React.Component {
  constructor(props) {
        super(props);
        this.state = {
            url: '',

        };
        this.setURL = this.setURL.bind(this);
  }

  setURL(page) {
        this.setState({
            url: page
        });
        console.log("Parent url: " + this.state.url);
  }

 render(){
  return(
    <MuiThemeProvider>
        <Router>
            <div className="App">

                <Route path="/" component={()=>(
                    <div>
                        <Header/>
                        <HealthForm changeUrl={this.setURL} urlProp={this.state.url}/>)}>/>
                    </div>)}/>

                <Route path="/path1" component={ProductForm}></Route>
                <Route path="/path2" component={xForm}></Route>
                <Route path="/path3" component={yForm}></Route>
                <Route path="/path4" component={zForm}></Route>

            </div>
        </Router>
    </MuiThemeProvider>
  );
 }
}

HealthForm

class HealthForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        exampleURL: '',
        exampleURLError: '',
        status: '',
        showStatus: false
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
 }

 validate = () => {
 //…checks for input errors
           }
 shouldComponentUpdate(nextProps, nextState) {
        return nextProps !== nextState;
    }

 handleChange(event) {
    this.setState({
        [event.target.name]: event.target.value
    });
 }

 handleSubmit(event) {
    event.preventDefault();
    const err = this.validate();
    let that = this;
    if (!err) {
                       this.setState({
            exampleURLError: ''
        });
        console.log(this.state);
        var data = this.state.exampleURL

         fetch('http://somehost/health', {
                    method: 'POST',
                    body: JSON.stringify(data)
                })
                .then((res) => {
                    var promiseStatus = res.text();
                    promiseStatus.then(function (value) {
                        console.log("StatusHA: " + value);
                        that.setState({
                            status: value,
                            showStatus: true
                        });

                        if (that.shouldComponentUpdate(that.state.jarvisURL, that.props.urlProp)) 
                            that.props.changeUrl(that.state.jarvisURL);
                    });
                }).catch((error) => {
                    console.log("Error: " + error);
                });
    }
 }

 render() {
        return (
            <form>  
            <TextField
              ...
            />
            <br/>

             <Button variant="contained" size="small" color="primary" onClick={e => this.handleSubmit(e)} >
                Check
            </Button>
            <br />  <br /> 

              ...

            </form>  
        );
 }


}
export default HealthForm;

All other forms are pretty similar to HealthForm.

How can i reorganize my code to make HealthForm the parent component? Or is making a brand new parent component with all the forms being its children a better option? If so, any suggestions?

EDIT

I made the changes Snaz suggested which sucessfully sends the url to App's state but now

 this.props.changeUrl(url);

causes the whole app to refresh?

1 Answer 1

0

Why don't you pass a function to HealthForm, that will change property of App's state and by changing state it will refresh and send this to other forms? Something like this:

App:

class App extends React.Component {
state = {
    url: ''
}

foobar(page){
    this.setState({
        url: page
    });
}

 render(){
  return(
[code here...]
                    <HealthForm changeUrl={this.foobar}/>
[code there...]
  );
 }
}

And in HealthForm in handleSubmit you just call:

this.props.changeUrl(url);

This should give the page to App and then you can pass this url to other forms in similar way showed here: https://github.com/ReactTraining/react-router/issues/4105

9
  • That's exactly what I have been trying out but couldn't get it quite right. Much appreciated. The only thing i changed from your suggestion is that I made a constructor for App. Now i get this error: Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
    – Dendin
    Commented Jul 28, 2018 at 22:06
  • The problem that's causing the warning is that i have HealthForm setState in my fetch call that gets the values of the promise returned. Looking at that right now
    – Dendin
    Commented Jul 28, 2018 at 22:23
  • I moved this.props.changeUrl(url); to be part of the fetch call and it fixed the warning. The page is still refreshing though
    – Dendin
    Commented Jul 28, 2018 at 22:57
  • If your page is refreshing in loop, use shouldComponentUpdate and check if nextState-> url is different than current url in state, if so, then return true, otherwise return false. This should make to render only if page url changed. reactjs.org/docs/react-component.html#shouldcomponentupdate
    – Snaz
    Commented Jul 29, 2018 at 6:57
  • with shouldComponentUpdate it re-renders only when the url changes as you said, but I need it to not do that regardless if the url state is changed. Is that possible? I have some user info that needs to be displayed after i do the health api call and that is never showed bc of the re-render resets the page.
    – Dendin
    Commented Jul 29, 2018 at 19:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.