trufflesuite/drizzle-react-legacy

Connecting drizzle values to state

Bowfish opened this issue · 4 comments

Is it possible to connect the fetched values from drizzle to the state?

There are two components in the new drizzle tutorial ReadString.js and SetString.js. I would like to combine these two components that the value myString of the component ReadString.js is the value of an input filed (<input type='text' value={this.state.myString} onChange={this.onChange} />. After the value is changed and the form will be submitted the value should be written to the contract storage with cacheSend. The render function would look like this:

  render() {
    
    // get the contract state from drizzleState
    const { MyStringStore } = this.props.drizzleState.contracts;

    // using the saved `dataKey`, get the variable we're interested in
    const myString = MyStringStore.myString[this.state.dataKey];

    if (myString) {
      return (
        <div>
          <p>My stored string: {myString && myString.value}</p>
          <input
            type="text"
            name='myString'
            value={this.state.myString}  // How can I set this.state.mySring which was feteched with const myString = MyStringStore.myString[this.state.dataKey]; to this.state.myString. I can not use setState in the render function
            onChange={this.onChange}
          />
          <div>{this.getTxStatus()}</div>
        </div>
      );
    }
  }

My problem is that the value of myString is fetched in the render() function (const myString = MyStringStore.myString[this.state.dataKey];) and in the render() function it is not possible to call setState.

What is the recommended way to do this?

Yes it is possible, the actions and reducers are just for that.

The reducer will update the state and the action will pass the value to the reducer.

A reducer will look like:

export function myString(state = '', action) {
    switch (action.type) {
        case 'ADD_MY_STRING':
            return action.myString;
        default:
            return state;
    }
}

You can dispatch the action directly or create a file.

const mapDispatchToProps = (dispatch) => {
  return {
    addMyString: (myString) => dispatch({type: 'ADD_MY_STRING', myString})
  };
};

You use it in your code as:

this.props.addMyString("Hello World");

@Bowfish Are you trying to initialize the value of the input text box with the contract state? If so, you can just do it from props: https://stackoverflow.com/questions/40063468/react-component-initialize-state-from-props

@Bowfish is your question answered?
If so maybe this can be closed :)

Thanks for checking up on this @soundyogi, closing for inactivity. Will open again if OP or someone else is having trouble.