0

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?

1
  • Try this: const [value, setValue] = React.useState("set a status"); Commented Jul 25, 2022 at 6:40

1 Answer 1

1

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)} />
  )
}
Sign up to request clarification or add additional context in comments.

2 Comments

How to use my StatusContext then? still the error exist
Sorry I was slow to respond, but I have now edited the answer, hopefully answering what you asked for :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.