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

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



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nico Antonelli