Next.js Discord

Discord Forum

Set global variable before server-actions get evaluated

Unanswered
Australian Terrier posted this in #help-forum
Open in Discord
Australian TerrierOP
Is there a way to set a global variable before server-actions get evaluated?

The global is from an external package, so I can't just add a setter-function in the module. You set it with a "setGlobal" function.

"use server"
import { getGlobal } from "external-package"

export default async function myAction() {
  console.log(getGlobal()) //Global should have been set before it gets here
}


Ideally this wouldn't require adding code / imports to every single file with actions as the global is needed in most of them.

As far as I can tell this can't be done from middleware, since middleware runs in a separate process.

(I am aware of the danger of cross-talk, the global is a getter-function that returns request-specific values)

4 Replies

Britannia Petite
just do what ever you want to do before calling your server action

export const Button = ()=> {
  const handleClick = async () => {
    // do somehting here
    // ...
    // call action
    await action();
    // or do something here
  }

  return (
      <button onClick={handleClick}></button>
  )
}
Australian TerrierOP
How would this be done with useFormState from a client component?
Britannia Petite
maybe you can try :

 const [state, dispatchAction] = useFormState(yourServerAction, initialState);

and then you can do somehting based on state, which will be equal to the value returned in your action
Australian TerrierOP
Thanks! I'll give that a shot