Reputation: 75
I am new to type script and I am trying to set the state in react using use state hook and type script.
const intialState: State ={
items: [],
value: "",
error: null
}
const [data, setData]= useState([intialState]);
return (
<>
{
data.items.map(x) => (
//my html component to be displayed.
)
}
</>
)
but I am getting the below error. Can any one tell me.
Upvotes: 2
Views: 7003
Reputation: 282160
You need to specify type for useState. Since its an array of your state object you can write it like
const [data, setData]= useState<State[]>([intialState]);
Also make sure you define a type for your state's object
interface ErrorType {
status: Number // more keys and their types here
}
interface MyDataType {
items: ItemType[],
error: ErrorType | null,
value: string,
}
post that you can use it with useState like
const [data, setData]= useState<MyDataType[]>([intialState]);
Your data is an array of objects and when you update the state you need to merge the values. For that you can use functional setState
var updatedDataObj = { items: ["a","b","c"], error: "404", value: "xyx", };
setData(prevData => [...prevData, updatedDataObj]);
Upvotes: 1
Reputation: 1061
I guess this was what you tried to achieve. Make sure you define your State type correctly, not importing from some other packages
interface State {
items: any[];
value: string;
error: string | null;
}
const MyComponent: (props) => {
const intialState: State ={
items: [],
value: "",
error: null
}
const [data, setData] = useState(intialState)
return (
<>
{
data.items.map(x) => (
//my html component to be displayed.
)
}
</>
)
}
Upvotes: 1
Reputation: 42606
First, we should check if there is an interface mismatch between State
, and the initialState
object. It will help if you can post the type definition of State
.
In addition, you should supply the useState
hook with the generic type parameter of State[]
const [data, setData]= useState<State[]>([intialState]);
Upvotes: 3