Reputation: 841
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!
Upvotes: 0
Views: 93
Reputation: 3359
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;
Upvotes: 0
Reputation: 4870
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;
Upvotes: 1