2

Getting error

Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

in a next.js environment when I try to use Zustand inside a utility function /utils/myfunction.js as:

import { connectToDatabase } from "./mongodb"
import {userStore} from '@/utils/store'

export async function userSubs(userId, token) {
  const { db } = await connectToDatabase()

  const userSubs = userStore(state => state.userSubs)
  const setGUserSubs = userStore(state => state.setGUserSubs)
  ...

how can I store/retrieve states with Zustand in a function or api then ? can't find a documentation about it

m4tt
  • 825
  • 1
  • 11
  • 28

1 Answers1

4

According to the official documentation this can be achieved with the utility functions that are attached to the hook prototype

import { connectToDatabase } from './mongodb'
import { useStore } from '@/utils/store'

export async function userSubs(userId, token) {
  const { db } = await connectToDatabase()
  
  // Get state
  const userSubs = useStore.subscribe(() => {}, state => state.userSubs)
  ...
  // Set state
  useStore.setState({ userSubs: ... })
  ...

Check out the link above for more examples about listening and destroying those listeners.

Nico Antonelli
  • 185
  • 1
  • 12
Ahmed Mohamedeen
  • 328
  • 3
  • 11
  • useStore.setState worked for me. Thank you. Just one thing: you're importing the store as "userStore" (line 2), but using it as "useStore" (I don't think it will cause much confusion, but just in case you want it to be consistent). edit: I already corrected it and added some comments :) – Nico Antonelli May 04 '22 at 15:23