0
votes

I have a react component with a form for updating database records. Here's the thing: the data is loaded with React-Relay QueryRenderer component as follows:

class Update extends Component {
   //constructor..
   //some stuff
   render() {
    return(
      <QueryRenderer
        environment={environment}
        query={UpdateQuery}
        render={({error, props}) => {
        //validations
          return (
            <Form loading={this.state.loading}>
            //inputs
            </Form>
           )...
      }/>
    )}

The props variable is supposed to store the result from server response if successful. However, I need to call the update with this.state values. I need a way to setState with props values.

I have tried with componentDidMount and using refs both string refs and callback ones to get defaultValue from Inputs. I got undefined values when calling this.refs

For now, it works if I call a function within QueryRenderer render function that sets the state with props if state is empty. E.g

function initValues(props){
  if(!this.state.name)
    this.setState({name: props.result.name})
}

But it results in an anti-pattern (pure render method) that I need to solve.

Edit: For anyone wondering how I solved this. Thanks to charlie's answer I managed to create a UpdateForm component wrapper that receives the props from QueryRenderer, and in order to update my parent's component state I passed my handleChange function as props to my FormUpdate component

1

1 Answers

2
votes

Use componentWillReceiveProps in your Form component

class Form extends React.Component {

    ...

    componentWillReceiveProps(nextProps) {
        if (nextProps.loading) return
        this.setState({
           name: nextProps.name
        })
    }

    ...
}

This will only set the state once as soon as the data is available, since QueryRenderer only calls render once after the data has loaded.