0

i have an array of strings and a variable of type string and when i press on the button Next which is in the Step Wizard form i want to concat that Variable to the Array using a callback function from child to parent component the problem is that it's not working as i want it to be it keeps adding that same variable again and again even i did an if statement i didn't know what to do to solve it

the parent component function

  myCallback = () => {

    if (this.state.modules.includes(this.state.moduleTitle)) {

        this.setState({ modules: this.state.modules });
    }
    //works fine when there are no modules
    if (this.state.moduleTitle == "") {
        this.setState({ modules: this.state.modules });
    }
    else {

        this.setState({ modules: this.state.modules.concat(this.state.moduleTitle) })
    }

}

the " moduleTitle " is that string variable and " modules " is the array of strings

the child component

continue = e => {
    e.preventDefault();
   // this.setState({ value: "full" });
    this.props.callbackFromParent();
    this.props.nextStep();

}

the continue function is used to go to the next step of the form

1 Answer 1

2

It looks like all you need to do is to pass the new moduleTitle back via your callback:

continue = e => {
    e.preventDefault();
    const currentTitle = this.props.title // or whatever your prop is called
    this.props.callbackFromParent(currentTitle);
    this.props.nextStep();
}

and deal with it at the other end:

myCallback = newModuleTitle => {
  const currentModules = this.state.modules
  if (newModuleTitle !== '' && !currentModules.includes(newModuleTitle)) {
    this.setState({ modules: [...currentModules, newModuleTitle] })
  }
}
Sign up to request clarification or add additional context in comments.

8 Comments

didn't get your question about the current title if it's from state or event
where is the moduleTitle? In the state, props, or on the button?
it's in the state of the parent component and i passed it as a props to the child
it's still the same problem when i press Next it's fine and when i go back and press again next it adds the newModuleTitle again despite i have that first if statement but it's not working
Ok, although you could just use the state in the parent, it's better practice to pass the data back with the click event, so that changes are treated as single atomic entities.
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.