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
You need to set
keepAlive={true}
With
StrictMode
, every component getsmounted
->unmounted
->mounted
, and withkeepAlive
equal totrue
, it will maintain the promise state.https://stackblitz.com/edit/vitejs-vite-w7hy6e?file=src%2Fexample.tsx
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.