Async rendering on the server? #143
-
Hello! I was playing around with nano-jsx and tried to render some components on the server, it works great! The only thing that I was not been able to do is to render async components like this: const ComponentWithPromise = async () => {
const message: string = await new Promise((resolve) => {
setTimeout(() => {
resolve('Hello World With Promise')
}, 500)
})
return <div>{message}</div>
} Is there a way to do this? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
You can't render asynchronously inside But you can do the following: class ComponentWithPromise extends Component {
static async message() {
const message: string = await new Promise(resolve => {
setTimeout(() => {
resolve('Hello World With Promise')
}, 500)
})
return message
}
render() {
return <div>{this.props.message}</div>
}
}
const main = async () => {
const message = await ComponentWithPromise.message()
const app = renderSSR(<ComponentWithPromise message={message} />)
console.log(app)
}
main() |
Beta Was this translation helpful? Give feedback.
-
You can easily send data deeply down: // import _state from somewhere from nano-jsx
import { _state } from '../state.js'
const getData = () => new Promise(resolve => setTimeout(() => resolve('hello'), 1000))
class App extends Component {
render() {
return (
<ul>
<li>Nano JSX App</li>
<li>second</li>
<li>{_state.get('some-unique-key')}</li>
</ul>
)
}
}
const main = async () => {
const data = await getData()
const app = renderSSR(() => {
_state.set('some-unique-key', data)
return <App />
})
console.log(app)
}
main()
I have experimented with it. But the way nano-jsx is build, it is not possible to add it. I would have to make too many breaking changes. And I like how it is now. There is always a way around async components, by knowing when and where you need the data. |
Beta Was this translation helpful? Give feedback.
You can easily send data deeply down: