DEV Community

Macry Poe
Macry Poe

Posted on

How can I pass and call functions into another component without props to create a "redo bar"?

I want to create a component that allows the user to use a "retry" option to invoke a failed function, but this function should be redefined every time this "retry" button is prompt. For example, this is the Google retry message:

Image description

I thought of using Redux.js but found out that passing functions through it is a really bad practice. Prop drilling is not an option (this app has a lot of sub-components).

Has anyone encountered this situation? I'm sure this concept is pretty common.

Some code examples:

const App = () => {
   return (
      <div>
         <Alert />
         <CompA />
         <CompB />
      </div>
   )
}

const Alert = () => {
   return (
         <button onClick={someFunction}>
            Retry
         </button>
   )
}

const compA = () => {
   const getData = async () {
      try {
         // fetch some data... 
      }
      catch {
         setUserAlert(() => getData())
      }
   }
   return (
      {data}
   )
}


const compB = () => {
   const postData = async () {
      try {
         // post some data... 
      }
      catch {
         setUserAlert(() => postData())
      }
   }
   return (
      {data}
   )
}
Enter fullscreen mode Exit fullscreen mode

Thanks!

Top comments (0)