Bittu Joshi
Bittu Joshi

Reputation: 528

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

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);

enter image description here

This solution is not working for me.

Upvotes: 3

Views: 10487

Answers (4)

razsbg
razsbg

Reputation: 41

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);

Upvotes: 4

Bhavesh Daswani
Bhavesh Daswani

Reputation: 725

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);

Upvotes: 3

Joseph King
Joseph King

Reputation: 5219

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.

Upvotes: 2

Asad Ashraf
Asad Ashraf

Reputation: 1645

There are 2 solutions:

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

Upvotes: 1

Related Questions