TyForHelpDude
TyForHelpDude

Reputation: 5001

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> { ...

Upvotes: 0

Views: 7348

Answers (2)

Vinzzz
Vinzzz

Reputation: 11724

This seems to have changed since...

If you look at React type definitions (index.d.t, React 16), you see that setState method signature in Typescript is :

class Component<P, S> {
...
  setState<K extends keyof S>(state: Pick<S, K>, callback?: () => any): void;
...
}

Sis our component state, in your case it's IWebPartState

Look at this SO question to understand what it means, but to make it short: you don't have to make your interface properties optional, yet you can pass only a subset of them to setState

Upvotes: 2

Hardik Modha
Hardik Modha

Reputation: 12746

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.

Upvotes: 2

Related Questions