Sole
Sole

Reputation: 3340

React initialise state based on object

If my data is in this structure from an api:

{
  title: "Title", 
  id: 1,
  description: "example desc"
}

What would I pass in as the initial value to the state object? i.e

interface ObjectData {
    title: string,
    id: number,
    description: string
}

const [fetchData, setFetchData] = React.useState<ObjectData>(?// here);

Upvotes: 0

Views: 105

Answers (2)

m5khan
m5khan

Reputation: 2717

Either if you have a default value to set (perhaps a mock) then you can set that object of type ObjectData.

for example

const defaultData: ObjectData = {
 title: 'x',
 id: -1,
 description: 'xyz',
};

...
const [fetchData, setFetchData] = React.useState<ObjectData>(defaultData);

Otherwise if you don't have default Data and you will get the data in the later time for example via an async API, then leave it empty. The type of fetchData will automatically be fetchData: ObjectData|undefined

const [fetchData, setFetchData] = React.useState<ObjectData>();

Alternatively you can explicitly typecast the empty object as ObjectData

const [fetchData, setFetchData] = React.useState<ObjectData>({} as ObjectData);

I would leave the default value empty if I will get the data in the later time.

Upvotes: 1

Dan
Dan

Reputation: 386

I think you can do this:

{
  title: "Title", 
  id: 1,
  description: "example desc"
}

const [fetchData, setFetchData] = React.useState({title, id, description});

Grabbed from here: Saving object in React.useState

Upvotes: 1

Related Questions