iamjpcbau
iamjpcbau

Reputation: 404

React.js: Get specific value as a string from state array (hooks)

I want to get a specific value in my state array

The state array looks like this if I do console.log

profileModule  
(2) […]
​
0: Object { moduleId: "4E948025-1F1B-41E2-A18D-55AD8646810B", module: "Client Maintenance", description: "Client Enrollment", … }
​
1: Object { moduleId: "C77C1031-2714-483D-AE59-21C9CD5EBAEF", module: "Bank Maintenance", description: "Bank Enrollment", … }
​
length: 2
​
<prototype>: Array []

I want to get the moduleId and set it as String

I tried this, but it doesn't work. It says undefined.

useEffect(() => {
    const moduleId = profileModule.moduleId
    console.log("moduleId ", moduleId)
  }, [profileModule]);

Any help would do. TIA

Upvotes: 0

Views: 125

Answers (1)

Joe Lloyd
Joe Lloyd

Reputation: 22513

Profile Module is an array

You need to get the index of the profile module you would like to retrieve.

useEffect(() => {
    const moduleId = profileModule[0].moduleId // gets the 1st index
    console.log("moduleId ", moduleId)
  }, [profileModule]);

But I don't think you want this to be static. Do you know what index you want to retrieve?

To Retrieve a list of IDs

You can use memo or callback on this code if you want to optimise.

const idsArray = profileModule 
  ? profileModule.map(({moduleId}) => moduleId);
  : [];

Upvotes: 1

Related Questions