simo
simo

Reputation: 24600

State is changed, but component is not refreshed

I am changing the state and I can see in the console.log the new state, however, the TextArea does not show the new state, but only when its first displayed.

Here is my implementation:

import React, {Component} from 'react';
import {TextArea} from "semantic-ui-react";

class Output extends Component {

    static myInstance = null;
    state = { keys:[] }

    updateState(){
        // this method is called from outside.. 
        this.setState({ keys:this.state.keys.push(0) });
        // I can see that keys are getting increase
        console.log(this.state.keys);
    }

    render() {
        return (
            <TextArea value={this.state.keys.length} />

        );
    }
}

TextArea will keep showing 0, although the length of state.keys increases..

Any idea?

Upvotes: 1

Views: 72

Answers (3)

Anton Dmitrievich
Anton Dmitrievich

Reputation: 172

Here is the working example

Firstly you should call your function to update the state

Example on jsfiddle

class Output extends React.Component {

 static myInstance = null;
 state = { keys:[] }

 componentDidMount(){
    this.updateState();
 }

 updateState() {
    const newKeys = [...this.state.keys,0]
  this.setState({ keys:newKeys });
 }
 onTextareaChange(){}

 render() {
  return (
    <textarea value={this.state.keys.length} onChange= {this.onTextareaChange} />
  );
 }
}

ReactDOM.render(<Output />, document.querySelector("#app"))

Upvotes: 0

amdev
amdev

Reputation: 7460

you dont call your updateState function to update your state , it just exists over there, for pushing 0 to your state in order to reRender your component with new state, you can call your method in componentDidMount like below:

componentDidMount = () => {
  this.updateState()
}

this will excute your updateState function immediately after component mounts into the dom.

Upvotes: 0

dotnetdev4president
dotnetdev4president

Reputation: 552

Never mutate the state. To update the state, use this syntax:

this.setState(prevState => ({
  keys: [...prevState.keys, newItem]
}))

Upvotes: 3

Related Questions