dai-shi / react-hooks-global-state

[NOT MAINTAINED] Simple global state for React with Hooks API without Context API

Home Page:https://www.npmjs.com/package/react-hooks-global-state

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Argument of type '"cart"' is not assignable to parameter of type 'never'

FutureKode opened this issue · comments

I have a NextJs project with typescript. I'm seeing the above error with useGlobalState and reducer style.

const [cart] = useGlobalState("cart") <-- Argument of type '"cart"' is not assignable to parameter of type 'never'

But I'm not sure what the problem is at it looks the same as the examples. Any ideas?

Hi, I need some more information.

  1. how does createGlobalState look like? does it initialize { cart: ... }?
  2. can you repro the issue without nextjs? a codesandbox repro would be nice.

Hi @dai-shi

This is the relative code:

import { createStore } from "react-hooks-global-state"

interface State {
  cart: Array<ICartItem>
  cookiesNoticeSeen: boolean
}

type Action =
  | { type: "rehydrate"; payload: any }
  | { type: "addItem"; item: ICartItem }
  | { type: "removeItem"; id: string }
  | { type: "setCookiesNoticeSeen" }

const defaultState: State = {
  cookiesNoticeSeen: false,
  cart: [],
}

const initialState: State = defaultState

const saveStateToStorage = ({ getState }: { getState: () => State }) => (
  next: Dispatch<Action>
) => (action: Action) => {
  const returnValue = next(action)
  if (isBrowser()) {
    localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(getState()))
  }
  return returnValue
}

export const { dispatch, useGlobalState } = createStore(
  reducer,
  initialState,
  applyMiddleware(saveStateToStorage)
)

It looks good...
Does removing middleware change things?
Can you repro with codesandbox?

I have found the lines in my code that are causing the issue.

case "rehydrate":   
      console.log('rehydrating', action)
      return action.payload

If I remove this code from my reducer then the errors go away

@dai-shi yep sorry about that, reworked my code and the error is gone 👻