0

I have simple structure:

interface IToast {
    text: string,
    setShow: Function,
    show: boolean,
}

const defaultToasts: IToast[] = [];
const [toasts, setToasts]: [IToast[], (toasts: IToast[]) => void] = useState(defaultToasts);

I want to add new element to existing array, but for some reason, after that:

let toast: IToast = {
    text: notification,
    setShow: () => { },
    show: true
}

setToasts([...toasts, ...toasts.concat(toast)]);

This item didn't get added properly to array, he rewrite entire array.

How can I do this?

UPDATED

I try @BrianThompson and @jared variant but it doesn't work for me, first element added correctly, but next one rewrite first. I think problem can be from defaulToasts, but not sure.

I use setState in useEffect hook, maybe problem come from this.

useEffect(() => {
    if (connection) {
        connection
                .start()
                .then(() => {
                    console.log("ready")
                    connection.on("ReceiveNotification", (notification) => {
                        console.log("New notification")
                        let toast: IToast = {
                                text: notification,
                                setShow: () => { },
                                show: true
                        }
                        setToasts([...toasts, toast]);
                    });
                })
                .catch((error) => console.log(error));
}, [connection]);
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
ArtemiZ Studio
  • 167
  • 2
  • 8
  • 1
    Just do `[...toasts, toast]`. [`concat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat) will return a new array with the new value appended to it. All you need is the new value. – Brian Thompson Mar 29 '21 at 23:50
  • `setToasts(oldToasts => [...oldToasts, toast])` – jered Mar 29 '21 at 23:50
  • 1
    Does this answer your question? [Correct modification of state arrays in React.js](https://stackoverflow.com/questions/26253351/correct-modification-of-state-arrays-in-react-js) – Emile Bergeron Mar 29 '21 at 23:51
  • Updated question – ArtemiZ Studio Mar 29 '21 at 23:57
  • what is `defaultToasts` (its value)? – Lith Mar 30 '21 at 00:00
  • 1
    Now you've got a stale closure. Use the callback updater: `setToasts(prev => ([...prev, toast]))` – Brian Thompson Mar 30 '21 at 00:00
  • @BrianThompson thanks for the answer, but how can i do this in typescript? i got error: `Argument of type '(prevState: any) => any[]' is not assignable to parameter of type 'IToast[]'.` – ArtemiZ Studio Mar 30 '21 at 00:20
  • u just "brutoforce" solution and that `setToasts(((prevState: any) => ([...prevState, toast])) as unknown as IToast[]);` work as excepted now. But i hope someone give me detail explanation about this behaviour – ArtemiZ Studio Mar 30 '21 at 01:16

0 Answers0