skip to Main Content

I am using below package react-if .
https://www.npmjs.com/package/react-if

but my child component is not rendering. I am trying like this

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <Example Component={App} />
  </React.StrictMode>
);

here is my Example component.

export const Example = ({ Component }) => {
  const fetchData = () => {
    return new Promise((resolve, reject) => {
      // Simulating an asynchronous operation (e.g., fetching data from a server)
      setTimeout(() => {
        console.log('oooooooooo');
        // Simulating a successful response
        const data = { message: 'Data fetched successfully' };
        return resolve(data);

        // Simulating an error
        // reject(new Error('Failed to fetch data'));
      }, 2000); // Simulating a delay of 2 seconds
    });
  };
  return (
    <div>
      <If condition={fetchData()}>
        <Fallback>Loading data ...</Fallback>
        <Then>
          {(data) => (
            <>
              <span>Here ish your data:{JSON.stringify(data)}</span>
              <Component />
            </>
          )}
        </Then>
        <Else>{(error) => <span>Failed to load data because </span>}</Else>
      </If>
    </div>
  );
};

Some time it show component .. some time not .. don’t know where I am doing wrong

here is my code
https://stackblitz.com/edit/vitejs-vite-gtdrmg?file=src%2Fexample.tsx,src%2FApp.tsx,src%2FApp.css,src%2Fmain.tsx&terminal=dev

2

Answers


  1. You need to set keepAlive={true}

    keepAlive?: boolean
    False (default): promises are cancelled before each unmount
    True: promises can be fulfilled even after a component unmount or a change to promise prop

    With StrictMode, every component gets mounted -> unmounted -> mounted, and with keepAlive equal to true, it will maintain the promise state.

    <If condition={fetchData()} keepAlive={true}>
            <Fallback>Loading data ...</Fallback>
            <Then>
              {(data) => (
                <>
                  <span>Here ish your data:{JSON.stringify(data)}</span>
                  <Component />
                </>
              )}
            </Then>
            <Else>{(error) => <span>Failed to load data because </span>}</Else>
          </If>
    

    https://stackblitz.com/edit/vitejs-vite-w7hy6e?file=src%2Fexample.tsx

    Login or Signup to reply.
  2. The real problem of your code snippets is that there is a new fetchData call on every render, which returns a new promise on every call, which then waits for a new timeout.

    Look into caching the promise to only need to create a single instance.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search