Home > Blockchain >  Passing a function in parent, and params in child
Passing a function in parent, and params in child

Time:03-27

How can I pass a function in the parent component, but then have parameters inserted into that function from within the child? For example, here is my code:

parent.js

<MyComponent
     getData={myGetFunction()}
     saveData={mySaveFunction()}
/>

child.js

const onRefresh = useCallback(async (getData, saveData) => {

     const Response = await props.getData(props.config); // I want myGetFunction(props.config)
     props.dispatch( props.saveData(Response) ); // I want mySaveFunction(Response)

}, []);

In this code, the two passed functions would look like this:

  • myGetFunction()(props.config)
  • mySaveFunction()(Response)

Of course this is no good. So how do I get this:

  • myGetFunction(props.config)
  • mySaveFunction(Response)

CodePudding user response:

What you want is only possible if you rename the props for MyComponent.

function myGetFunction(config) {

}

function mySaveData(response) {
   
}

<MyComponent
   myGetFunction={myGetFunction}
   mySaveData={mySaveData}
/>

Then use prop destructuring in your child.

const MyComponent = ({myGetFunction, mySaveData}) => {

    const onRefresh = useCallback(async (getData, saveData) => {

     const Response = await myGetFunction(props.config)
     props.dispatch( mySaveFunction(Response) )

    }, []);


 ...
}

If myGetFunction is a function that returns the function that you want to use, then you can still do this, but call it like you did.

<MyComponent
   myGetFunction={myGetFunction()}
   mySaveData={mySaveData()}
/>

The function call in the child is identical.

If you cannot rename the props for some reasons, then you can assign it to a constant and reuse it.

<MyComponent
     getData={myGetFunction}
     saveData={mySaveFunction}
/>

const MyComponent = ({getData, saveData}) => {
    const myGetFunction = getData
    const mySaveFunction = saveData

   ...
}
  • Related