Reputation: 1396
I have this simple code in my index.tsx
let state = {};
window.setState = (changes: any) => {
state = Object.assign({}, state, changes);
ReactDOM.render(<App {...state} />, document.getElementById("root"));
};
but i get the error as
Property 'setState' does not exist on type 'Window'.
in my Dependencies i have the following
"dependencies": {
"@types/react": "^16.7.7",
"@types/react-dom": "^16.0.11",
}
I am following this React Auth
Upvotes: 0
Views: 2147
Reputation: 7526
To those saying it should be this.setState()
, I don't think it should. It's just unfortunate that the example given by that React Auth library is defining a weird and poorly named (in the context of React) global function called setState()
.
This is the example JavaScript given in your link:
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
let state = {};
window.setState = changes => {
state = Object.assign({}, state, changes);
ReactDOM.render(<App {...state} />, document.getElementById("root"));
};
/* eslint no-restricted-globals: 0*/
let initialState = {
isLoggedIn: false,
signup: function () {
window.open(
"https://auth0.com/signup?utm_source=stackblitz&utm_medium=devsponsor&utm_campaign=stackblitz-react",
"_blank"
);
}
};
window.setState(initialState);
You just need to extend window
to keep TypeScript happy:
declare global {
interface Window {
setState: (changes: any) => void;
}
}
let state = {};
window.setState = (changes: any) => {
state = Object.assign({}, state, changes);
};
Although it looks like a bad implementation unless I'm missing something. You should be using React's state (and/or something like Redux) rather than re-rendering the app when one of these properties changes.
Upvotes: 1
Reputation: 2860
I think it shouldn't be window.setstate
, it should be this.setstate({})
Upvotes: 0