Home > Net >  react Unable to retrieve the contents of an object
react Unable to retrieve the contents of an object

Time:12-22

I am using react.
I want to display the name of the object retrieved using find.

When I look at currentValue() in console.log(), I can see that the object has been retrieved. However, when I try to display the name of the retrieved object (currentValue().name), I get an error.
If anyone knows the reason, I would appreciate it if you could tell me.

error

Uncaught TypeError: Cannot read properties of undefined (reading 'id')

  const [state, setState] = useState<{id: number, name: string}[]>([])

  const currentValue = () => {
    return state.find((s) => {
      return s.name === props.groups.name;
    });
  };

    console.log(currentValue())
  console.log(currentValue().name)

CodePudding user response:

Your state may be undefined so that is why it shows an undefined error, plz find the state will get updated or not before you compare the state

CodePudding user response:

What if you structure the code in this way? Because in the current way, you are not passing a variable to the method when invoking it, so it cannot refer anything.

const [state, setState] = useState<{id: number, name: string}[]>([])

const find = (id: number) => {
   return state.find((_s) => { return _s.id === id; });
};

CodePudding user response:

currentValue() is your function and when you are calling that function at that time you are getting values returned for it.

So you can't directly call currentValue().name it is not making any sense here.

So just const obj = currentValue() is the solution according to your code.

Then you will get object return from curretValue();

Now just do obj. value you want to get.

  • Related