Home > database >  How to declare useState() initial value as null and then give it an object value later?
How to declare useState() initial value as null and then give it an object value later?

Time:07-06

enter image description here

As can be seen in the image, I want to declare a react state hook to the alert of my webpage. At first, I want that there is no alert shown. And whenever user is clicking some button, I want to show a success alert with a message (error alert if something goes wrong). I will call showAlert function to do this with message and type as function parameter. That's why there can be more than one type of alert. So, I created this alert object and attached hook with initial value "NULL". But the editor gives me this error.

Argument of type '{ msg: any; type: any; }' is not assignable to parameter of type 'SetStateAction<null>'. Object literal may only specify known properties, and 'msg' does not exist in type '(prevState: null) => null'.ts(2345)

So, can someone tell me how I can tell useState the object parameters that I will allot it in future. Or should I try to hide the website alert in some other way? Here is the code..

const [alert, setAlert] = useState(null);

const showAlert = (message, type) => {
    setAlert({
        msg: message,
        type: type,
    });

    setTimeout(() => {
        setAlert(null);
    }, 2000);

CodePudding user response:

You need to declare your useState a little differently

const [alert, setAlert] = useState<{ msg: any; type: any } | null>(null);

Another alternative is the use undefined

const [alert, setAlert] = useState<{ msg: any; type: any } | undefined>();

Hope that helps.

CodePudding user response:

You can do it below way for useState type

type AlertType = {
 msg: string;
 type: string; // you can specify enum also
}

const [alert, setAlert] = useState<AlertType|null>(null);

const showAlert = (message, type) => {
    setAlert({
        msg: message,
        type: type,
    });

    setTimeout(() => {
        setAlert(null);
    }, 2000);

CodePudding user response:

There are 2 solutions:

1: useState(null as any)
2: useState({ msg: any, type: any })

CodePudding user response:

From the looks of the error you mentioned, it seems you're using TypeScript.

One way to achieve the desired outcome is to use generics.

const [alert, setAlert] = useState<{
  msg: string;
  type: "success" | "error";
} | null>(null);

Furthermore, you can improve readability by adding an enum and a type.

enum AlertType {
  Success,
  Error,
}

type Alert = {
  msg: string;
  type: AlertType;
}

const [alert, setAlert] = useState<Alert | null>(null);
  • Related