0

So this is my parent component - it's getting a state set from it's child component when what component is updated which works great

const [filteredCases, setFilteredCases] = useState([]);

<ChildComponent
  setFilteredCases={setFilteredCases}
/>

What I would like to do is also call a function whenever the setFilteredCases state is updated .. so something like this

const [filteredCases, setFilteredCases] = useState([]);

function foo() {
  // do things
}

<ChildComponent
  setFilteredCases={setFilteredCases, foo}
/>

But doing so seems to break the state update and never calls the function .. have I got the syntax wrong here or is there a better way to implement what I'm doing here?

Any advice / guidance / links to documentation welcome!

2 Answers 2

1

Try using useEffect instead

const [filteredCases, setFilteredCases] = useState([]);
const foo = () => {
  // some changes

}

useEffect(() => {
  // filteredCases has been updated
  foo();

}, [filteredCases]);


<
ChildComponent setFilteredCases = {
  setFilteredCases
}
/>

const ChildComponent = ({
  setFilteredCases
}) => {
  // Call the function this way:
  setFilteredCases([]);
  return (
    // Send out something.
  );
};

export default ChildComponent;

Sign up to request clarification or add additional context in comments.

Comments

0

You can pass a state or method as a props from parent to child component.

Example:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

function App() {
  return (
    <div>
      <Welcome name="Sara" />
      <Welcome name="Cahal" />
      <Welcome name="Edite" />
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

Another Example :

const [filteredCases, setFilteredCases] = useState([]);

function foo() {
  // do things
}

<ChildComponent
  setFilteredCases={setFilteredCases}
  foo={foo}
/>

const ChildComponent = ({ foo, setFilteredCases }) => {

  const onHandleClick = () => {
    // Call the functions
    setFilteredCases('value');
    foo();
  }

  return (
    <button onClick={onHandleClick} >Click me</button>
  );
};

export default ChildComponent;

Comments

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.