type of custom object in typescript - reactjs

I'm new to typescript and I created this object:
const initialState = {
title: {
value: "",
error: false
},
amount: {
value: 0,
error: false
},
type: "Food",
time: new Date()
}
I want to use is as initial state of a useState. therefore I want to now what I need to passe as type to my useState.
const [Form, setForm] = useState< "what should come here?" >(initialState);
thanks in advance,

interface IState {
title: {
value: string;
error: boolean;
};
amount: {
value: number;
error: boolean;
};
type: string;
time: Date;
}
const [Form, setForm] = useState<IState>(initialState);

You could do something like this:
interface SomeName {
value: string;
error: boolean;
}
interface IState {
title: SomeName;
amount: SomeName;
type: string;
time: Date;
}
const initialState: IState = {
title: {
value: "",
error: false
},
amount: {
value: 0,
error: false
},
type: "Food",
time: new Date()
}
const [Form, setForm] = useState<IState>(initialState);

Related

Double map in React+Typescript

Maybe I'm missing something, but how should I properly double map in this case? Bcs I have error on secon map : Property 'map' does not exist on type '{ departure: { code: string; name: string; dateTime: string; }; destination: { code: string; name: string; dateTime: string; }; duration: string; }
const [result, setResult] = useState<ConversionData[]>([]);
type ConversionData = {
uuid: string;
airlinesCode: string;
price: {
amount: number;
currency: string;
};
bounds: {
departure: {
code: string;
name: string;
dateTime: string;
};
destination: {
code: string;
name: string;
dateTime: string;
};
duration: string;
};
};
useEffect(() => {
const api = async () => {
const data = await fetch("http://localhost:3001/flights").then((res) =>
res.json()
);
setResult(data);
console.log(result);
};
api();
}, []);
return (
<div className="App">
<h1>
{result?.map((value) => {
console.log(value)
return (
<div>
<div>{value.price.amount}</div>
{value.bounds.map((newvalue:any)=>{
<div>{newvalue.departure.name}</div>
})}
</div>
);
})}
</h1>
</div>
);
what I need to map
I've searched the internet for something similar, but I've hit the starting point, and I need to get to bounds -> departure -> name
Bounds in your type ConversionData is object. But at you data screenshot bounds should be array.
bounds: Array<{
departure: {
code: string;
name: string;
dateTime: string;
};
destination: {
code: string;
name: string;
dateTime: string;
};
duration: string;
};
}>;

How to remove the typing error I can't figure out what the problem is

I have such a component to which I pass the props
I get errors like this:
(property) buttons: {
key: string;
text: string;
iconPath: string;
isActive: boolean;
}[]
The type "{ buttons: { key: string; text: string; concat: string; is Active: boolean;
}[];
onChange: (key: string) => void; }" cannot be assigned to the type "IntrinsicAttributes".
The "buttons" property does not exist in the "IntrinsicAttributes" type.
The props look like this:
const [buttons, setButtons] = useState([
{
key: ${useId()},
text: "Trading",
iconPath: ${iconTrading.src},
isActive: false,
},
{
key: ${useId()},
text: "Banking",
iconPath: ${iconBanking.src},
isActive: true,
},
]);
const onNavigationChange = useCallback(
(key: string) => {
const newButtons = buttons.map((button) => ({
...button,
isActive: button.key === key,
}));
setButtons(newButtons);
},
[buttons]
);

Typescript UseContext React

I'm new to Typescript and react and am getting this error, on default card
I am trying to setup use context and will use it with use state or use reducer but I am having trouble wrapping my head around initial setup for this
Error:
Argument of type '{ cartitem: { id: number; name: string; description: string; price: string; }; addCart: () => void; removeCart: () => void; }' is not assignable to parameter of type 'CartContextType'.
Types of property 'cartitem' are incompatible.
Type '{ id: number; name: string; description: string; price: string; }' is missing the following properties from type 'ICart[]': length, pop, push, concat, and 29 more.ts(2345)
import React, { createContext } from 'react';
export interface ICart {
id: number;
name: string;
description: string;
price: string;
}
export type CartContextType = {
cartitem: ICart[];
addCart: (cart: ICart, totalAmount:number) => void;
removeCart: (id: number) => void;
};
const defalutCart={cartitem:{
id: 0,
name: 'string',
description: 'string',
price: 'string'},
addCart: () => {},
removeCart: () => { }
}
export const CartContext = createContext<CartContextType | null>(defalutCart);
Your variable defalutCart needs the property cartitem to be an array. With the correct spelling and changes, here is your updated code:
const defaultCart = {
cartitem: [
{
id: 0,
name: "string",
description: "string",
price: "string",
},
],
addCart: () => {},
removeCart: () => {},
};
Do you see how the object is now wrapped in an array? Please mark this as correct if it solves your problem.

react How to change the value of object in react array

development enviroment
・ react
・ typescript
state to update the member object in the state array.
I implemented is as follows.  
However, I get the following error and cannot implement it well.
errormessage
Type'(IMemberLavel | {Language: IMember;}) []'cannot be assigned to type'IMemberLavel []'
interface IMemberLevel {
member: IMember;
level: ILevel;
}
interface IMember {
id: number;
name: string;
}
interface ILevel {
id: number;
name: string;
}
interface ISearch {
name: string;
age: number;
groups?: IGroups[];
memberLavel: IMemberLevel[];
}
interface IState {
searchState: ISearch;
text: string,
display: boolean
}
const Index: FC = () => {
const [state, setState] = useState<IState>({
searchState: initialSearch,
text: '',
display: boolean
});
const onClickMember = (member: IMember) => {
setState({
...state,
searchState: {
...state.searchState,
memberLavel: [...state.searchState., { member : member }],
},
});
};
Postscript
const inithialMemberLavel: IMemberLevel = {
member: { id: 0, name: '' },
level: { id: 0, name: '' },
};
const initialSearch: ISearch = {
name: '',
age: 0,
groups: [],
memberLavel: inithialMemberLavel[]
}
The new member you're adding to memberLavel is missing level property, either add the property
setState({
...state,
searchState: {
...state.searchState,
memberLavel: [
...state.searchState.memberLavel,
{ member, level: { id: /* some number */, name: /* some name */ } },
],
},
});
or set it as optional in IMemberLevel interface
interface IMemberLevel {
member: IMember;
level?: ILevel;
}

React updating nested arrayelement via setState

I'm trying to set state of input fields.
I want to update specific input value when a key is pressed.
setState state looks fine, but I'm getting error on map function of render part.
(this.state.form[this.state.mode].form.map)
I don't understand why it breaks on map.
export type IMode = "login" | "forgot";
export interface IInput {
value: string;
error: string;
id: string;
name: string;
placeholder: string;
type: "text" | "password";
}
export interface IState {
isRequestPending: boolean;
backendError: string;
mode: IMode;
form: {
[key in IMode]: {
name: string;
method: string;
action: string;
fields: IInput[];
};
};
}
in constructor
this.state = {
isRequestPending: false,
backendError: "",
mode: "login",
form: {
login: {
name: "Login",
method: "",
action: "",
fields: [
{
value: "",
error: "",
id: "test",
placeholder: "Login",
type: "text",
name: "login"
}
]
},
.... and so on
}
};
private handleFormInput = (e, input: IInput, index) => {
this.setState((prevState) => ({
...prevState,
backendError: "",
form: {
...prevState.form,
[this.state.mode]: {
...prevState.form[this.state.mode],
fields: {
...prevState.form[this.state.mode].fields,
[index]: {
...prevState.form[this.state.mode].fields[index],
value: "it Works, but map crash"
}
}
}
}
}
You are converting fields into an object which doesn't contain a map method. Update your state like this
this.setState(prev =>({
/*...*/
fields : prev.form[this.state.mode].fields.map((field, i) =>{
if(i !== index) return field
return {
...field,
value : 'foo'
}
})
}))

Resources