javascript - React - handle state of value nested in initial object -
i trying handle input state of tasks nested in initial object. want set task value name in state datagoal object.
the initial state so:
the render method:
render(){ return( <div> <main classname="content"> <form onsubmit={this.onsubmit}> <div> {object.keys(this.state.datagoal).map( (key, index) => { return <div key={key}> <label>{this.state.datagoal[key].name}</label> <p>index: {index}</p> <div classname="input-wrap"> {object.keys(this.state.datagoal[key].tasks).map( (taskkey) => { return <div key={`task-wrap-${taskkey}`}> <p>{taskkey}</p> <input type="text" name="name" value={this.state.datagoal[key].tasks[taskkey].name} onchange={(e) => this.handleinputchange(e, key, taskkey)} /> </div> })} </div> <a classname="add-link" onclick={(e) => this.appendinput(e, key)}> {"+ add task"} </a> </div>; })} </div> <div classname="input-wrap"> <input classname="primary-btn" type="submit" value="set goal!" onclick={this.formreset} /> </div> </form> </main> </div> ); }
and handleinputchange function:
handleinputchange = (e, key, taskkey) => { console.log(this.state.datagoal[key].tasks); const value = e.target.value; const name = e.target.name; const datagoal = this.state.datagoal[key].tasks; const updatedtask = object.assign({}, datagoal[taskkey], { [name]: value }); this.setstate({ datagoal: object.assign({}, datagoal, { [taskkey]: updatedtask }) }); }
everything looks should work fine getting error "cannot read property 'tasks' of undefined" in handleinputchange. if console.log tasks gives me desired output:
does have clue please?
thank you, jakub
solved problem destructing state so:
handleinputchange = (e, key, taskkey) => { const value = e.target.value; const name = e.target.name; this.setstate({ datagoal: { ...this.state.datagoal, [key]: { ...this.state.datagoal[key], tasks : { ...this.state.datagoal[key].tasks, [taskkey] : { ...this.state.datagoal[key].tasks[taskkey], [name]: value } } } } }); }
Comments
Post a Comment