Do imports/globals work differently for app routing?
Unanswered
Knopper gall posted this in #help-forum
Knopper gallOP
Instead of calling
But my server components always render with
Any ideas what's going on here, or how I can effectively use global server-side state in my Next.JS app router codebase?
Thanks!
fetch(), I mocked out an API's data store using a const, kind of like this:import 'server-only';
import {cache} from "react";
import {revalidatePath} from "next/cache";
// mimics the data that will be stored by an external API
console.log("Setting initial state.")
export const state = {
foo: 1,
bar: 'baz'
};
// mimics the cached GET fetch() to the external API
export const getState = cache(async () => {
return state;
})
// mimics a POST fetch() to the external API
export async function updateStateAction(newFoo: number) {
state.foo = newFoo;
revalidatePath('/')
}But my server components always render with
{foo: 1}, even after calling into that action to update foo to a new value. And the "Setting initial state" log gets emitted on each page load. It's like this file is getting re-imported from scratch on each render, erasing that global state I had set up. I've already set my pages to force-dynamic so it's not a static render issue.Any ideas what's going on here, or how I can effectively use global server-side state in my Next.JS app router codebase?
Thanks!
15 Replies
Knopper gallOP
In this case, I'm talking about global state on the server.
i know what you are talking about
its not a thing
Knopper gallOP
I found this post that describes the same issue - and the workaround there works for me!
https://discord.com/channels/752553802359505017/1082068161047822358/1082091233863802932
https://discord.com/channels/752553802359505017/1082068161047822358/1082091233863802932
that is terrible practice
and you should not expect that to work
server-less functions do not talk to each other
Knopper gallOP
Yep - this isn't for production or going into Vercel, it's to quickly mock out a CRUD API.
sure. mock it correctly. dont take shortcuts that benefit nothing but 5 minutes of time
if its local use a file for state
dont use global.
Knopper gallOP
Is the use case from that linked thread valid though? That's more about expensive initialization than making a simple mock.
there is no use case imo that you should use global
Knopper gallOP
👠thanks for the help! I'll keep that in mind.