I'm new to next13 and I am having a hard time trying to figure out how can I retrieve redux state in a server component such as my main page.js
file. Can someone tell me the steps of getting that data?
You can access Redux state in a server component by importing your store and directly calling store.getState()
. The caveat being the server won't have access to state created/stored on the client, which will be the case if your state was initially set on the client (i.e. via useDispatch()
).
From my limited testing I've found that you need to set the state from a server component with store.dispatch(action(payload))
. If you need to make this dispatch from a client component, you can use a server action like so:
server component:
export default async function PageName() {
async function setStateFromServer(action, payload) {
// this is the server action
'use server';
store.dispatch(action(payload));
}
return (
<>
<ClientComponent stateSetter={setStateFromServer}/>
</>
)
client component:
'use client';
export const ClientComponent = ({ stateSetter }) => {
const handleSetState = () => {
stateSetter(someAction, somePayload)
}
return ...
}
Then finally, you can access your state:
export default async function SomeServerComponent () {
const state = store.getState();
...
}