Pirzada
Pirzada

Reputation: 4713

React.js: Re-render component data on add

New object is added fine and gets newTodos with updated data. In render function I get this.props.todoList which is an array of objects to be displayed.

How can I update todoList with newTodos to display this new data?

I can do this with setState({todoList: newTodos}) and in render function get this.state.todoList etc but I don't want to keep big objects (in future) in state. Instead I want to use props.

Any suggestion?

var React = require('react');

var TodoList = require('./todo-list.js');

var App = React.createClass({
    getInitialState: function () {
        return { filter: 'active' };
    },
    onAdd: function (txt, color) {
        console.log('txt: ' + txt + ', color: ' + color);
        var newTodos = this.props.todoList.push(Map({ txt: txt, isCompleted: false, color: color }));

        this.forceUpdate();
        // this.setState(this.state);
    },
    render: function () {
        var { todoList } = this.props;
        return (
            <div>
               <TodoList todoList={todoList}/>
            </div>
        );
    }
});


module.exports = App;

Upvotes: 1

Views: 276

Answers (1)

Ilya_S
Ilya_S

Reputation: 204

Props only purpose in React is to transfer data from parent component to children in order to notify them that state has changed.
You will have to maintain state because it's the right React way to control application components and maintain state integrity.
Not sure why you prefer props over state as you'll have to store data somewhere anyway, but the provided solution with forceUpdate() will soon make your app state inconsistent as long as you'll add more and more components.

Upvotes: 1

Related Questions