Home > Software engineering >  React initialise state based on object
React initialise state based on object

Time:10-22

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);

CodePudding user response:

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

CodePudding user response:

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.

  • Related