score:2

Accepted answer

you can just put it into separate function, its a bad idea to access "this" in functional components

const [state, setstate] = react.usestate({
firstname: "john",
lastname: "doe",
id: "12345"});

const getfullname = () => {
    return `${state.firstname} ${state.lastname}`
}

score:1

the problem lies in the function usestate, which can accept either initialstate or a function producing it:

function usestate<s>(initialstate: s | (() => s)): [s, dispatch<setstateaction<s>>];

to fix, extract initalstate to a separate object:

const initialstate = {
    firstname: "john",
    lastname: "doe",
    id: "12345",
    getfullname():string {
    return `${this.firstname} ${this.lastname}`;
  },
};

const [state, setstate] = react.usestate(initialstate);

playground link

also, consider using an iife for constructing the initialstate:

const initialstate = ((firstname, lastname) => ({
    firstname,
    lastname,
    id: "12345",
    getfullname():string {
    return `${firstname} ${lastname}`;
  },
}))('john', 'doe');

Related Query

More Query from same tag