satya jha
satya jha

Reputation: 13

Updating nested states in reactjs

I have this state which is nested and I am having difficulty in setting state. Error:undefined is not an object (evaluating this.state.form) My initial state is :

this.state={
    activePage:0,
    visible:false,
    questionType:null,
    form:{
        title:'',
        description:'',
        pages:[{
            title:'',
            description:'',
            questions:[

            ]
        }]
    }
};

Now every time a user clicks, I need to add more object to pages array which should be having a title (''), description ('') and questions (empty list). I tried achieving this but it doesn't seem to be working.

let newForm={
     ...this.state,
     form:{
          ...this.state.form,
          pages:[
               ...this.state.form.pages,
               pageData
          ]
     }
 };
 console.log('newForm',newForm);
 this.setState({
     form:newForm
 });

This is how my pageData looks like

let pageData={
    title:'',
    description:'',
    questions:[]
};

Upvotes: 1

Views: 73

Answers (2)

Praveen Rao Chavan.G
Praveen Rao Chavan.G

Reputation: 2860

Whenever you see yourself in a situation where your state is getting complex or nested it means you should be rethinking you component structure, I mean you should be bringing in more granular components to manage their own state.

so why not move form object in your state to a different component completely.

I recommend creating a separate component for form object and let the form component manage the form state.

import React, { Component } from 'react';

class form extends Component {
    state = {
      form:{
            title:'',
            description:'',
            pages:[{
                title:'',
                description:'',
                questions:[

                ]
            }]
        }
    }

    render() {
    //Form content
    }
}

export default form;

more granular your components are more easy to manage and that's exactly the way you should be doing things in React.

Upvotes: 1

adiga
adiga

Reputation: 35202

You are setting the entire state in newForm. Just limit it to the form object:

let newForm = {
  ...this.state.form,
  pages: [
    ...this.state.form.pages,
    pageData
  ]
};

console.log('newForm', newForm);

this.setState({
  form: newForm
});

Upvotes: 1

Related Questions