How to use server-side, like w/ Next.js
jasonbarry opened this issue · comments
I'm curious how to set values in the store when fetching data server-side. Is SSR supported?
import React from 'react'
import App, { Container } from 'next/app'
import Store from './MyStore'
export default class MyApp extends App {
static async getInitialProps({ Component, ctx }) {
const pageProps = Component.getInitialProps ? await Component.getInitialProps(ctx) : {}
const res = await fetch('https://api.github.com/repos/zeit/next.js')
// how can you access `store` here?
// we're in a static method so props aren't available
store.set({
data: res.json()
})
return { pageProps }
}
render() {
const { Component, pageProps } = this.props
return (
<Container>
<Store.Container>
<Component {...pageProps} />
</Store.Container>
</Container>
)
}
}
Hey @jasonbarry, I'm not super familiar with this pattern. Could a singleton store work here?
https://undux.org/#api/createStore
(I'm planning to un-deprecate it, but still discourage people from using it)
@bcherny I'll give that a try. Out of curiosity, why is its use discouraged?
Singletons:
- Can’t be instantiated more than once. Eg. If you build a widget dashboard, each widget has a store, and you can have more than one instance of a widget per dashboard, it won’t work.
- Can’t be garbage collected. Even after the React component that used your store is unmounted, the runtime still can’t GC your store and its data.