Search code examples
typescript-typingsreact-typescript

`Type '{}' is not an array type. ` error throws when set the context


status context:

import * as React from "react";
export const StatusContext = React.createContext({});
export function StatusProvider({ children }:React.PropsWithChildren) {
  const value = React.useState("set a status");
  return (
      <StatusContext.Provider value={value}>
      {children}
    </StatusContext.Provider>
); }

when assign the value:

function SetStatus() {
const [status, setStatus ] = React.useContext(StatusContext);
return (
    <input value={status} onChange={(e) => setStatus(e.target.value)} />
)

}

getting an error as :

    TS2461: Type '{}' is not an array type.
    4 |
    5 | function SetStatus() {
  > 6 |     const [status, setStatus ] = React.useContext(StatusContext);
      |           ^^^^^^^^^^^^^^^^^^^^
    7 |     return (
    8 |         <input value={status} onChange={(e) => setStatus(e.target.value)} />
    9 |     )

Not able to get the fix. any one help me please?


Solution

  • When you use the useState hook, you get back an array containing the value and a function to set the value. You currently pass this array in as the value in your context. Try modifying your code like the snippet below, and see if the error goes away.

    export function StatusProvider({ children }:React.PropsWithChildren) {
      const [value, setValue] = React.useState("set a status");
      return (
        <StatusContext.Provider value={{status: value, setStatus: setValue}}>
          {children}
        </StatusContext.Provider>
      );
    }
    

    Edit: I changed the way you supply the value to the context provider here, so that now the context will be an object with status and setStatus as keys. Now you can read this in the consuming component, like this:

    import { StatusContext } from '..path/to/file';
    
    function SetStatus() { // assuming SetStatus is a component
      const { status, setStatus } = React.useContext(StatusContext);
      return (
        <input value={status} onChange={(e) => setStatus(e.target.value)} />
      )
    }