TyForHelpDude TyForHelpDude - 4 years ago 193
TypeScript Question

How to set state for individual state variable in react + typescript?

when I click button, "isLoading" set to true and loading gif seems in page, process simple here its click function;

private clickFunction(e): void {
this.state.isLoading=true; ..


so i expect this loading gif seems in page;

<div style={{"display":this.state.isLoading?"block":"none"}}><i className="fa fa-spinner fa-spin"></i></div>


but its not working.. whats wrong here? since if initial value of isLoading property set as true, gif seems on plageload so whats I think state not updating the render or ?

EDITED :
When I try to update only one property of state ts compiler throws this exception;
enter image description here
Whats worng with here ?

export interface IWebPartState {
status: string;
Name: string;
isLoading:boolean;
}
export default class Contact extends React.Component<IContactProperties, IWebPartState> { ...

Answer Source

You are setting state in a wrong way, Instead of doing this.state.isLoading=true, you should set state using setState as follows,

this.setState({
    isLoading: true
});

Read more about state here and setState here.

Edit: As you are using reactjs with typescript, You will need to make property optional in the type interface and you can do that using ?. Read more about it in optional properties section here

interface IGifLoadingState {
    isLoading?: boolean;
    status?: string;
}

After declaring properties optional, typescript will allow you to set any individual property in the state.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download