4

What I'm trying to achieve here is, I want the value to be updated in the imported class B's state by calling the B's function init() from the class A. I'm initializing a new Object of B class and calling the init function through the object.

Class A

  import B from 'b.js'

  class A extends Component{
      componentDidMount(){
          const b=new B();
          b.init("hey");
        }
   }

In Class B: I'm updating the state using the init function, but it appears that I'm getting setState is not a function error. I have also tried binding init function in the constructor, but the error stays the same.

    class B extends Component{
      constructor(props){
       super(props);
       state = {
            text:""
         }
       }

       init=(text)=>{
          this.setState({text})
        }
     }
3
  • 3
    That code doesn't seem like it would have that problem. (But it's also almost certainly an anti-pattern; use a constructor in B and a prop for the text.) Please update your question with a minimal reproducible example demonstrating the problem, ideally a runnable one using Stack Snippets (the [<>] toolbar button). Stack Snippets support React, including JSX; here's how to do one. Commented Feb 19, 2019 at 17:20
  • 2
    Your calling setState on a unmounted component, that doesn't make any sense. If you want to set the initial state, just do -> Object.assign(this.state, {text})
    – Keith
    Commented Feb 19, 2019 at 17:30
  • @Keith What if I want to update the state? The same method should work? Commented Feb 19, 2019 at 17:33

1 Answer 1

0

You don't really need init, that is what the constructor is for. You should pass in the text as a prop to component B when you create it:

import B from 'b.js';

class A extends Component {
    componentDidMount() {
        const b = new B({ initialText: 'hey' });
    }
}

Then you can set the state inside the constructor for B.

state = {
    text: prop.initialText,
};

Be careful though, setting the state from a prop is generally a bad idea. See the note block here https://reactjs.org/docs/react-component.html#constructor for more details.

3
  • I have multiple functions inside B, which I'm calling from class A. So I cannot send the values as props to that class. The params of each functions are different. Commented Feb 19, 2019 at 17:50
  • 2
    Then use a state on A and send them as params to the functions on B. If B isn't mounted, you can't use state on it. Make a service if you really want this design pattern Commented Feb 19, 2019 at 17:54
  • I'm not sure what your end goal is. Perhaps updating the question with what you currently have and what you are trying to accomplish would help.
    – csbarnes
    Commented Feb 19, 2019 at 17:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.