0

I'm having following json file,

[
    {
        "id" : 7,
        "intro": "intro_7"
       
    },
    {
        "id" : 8,
        "intro": "intro_8"
    }
]

Then I'm trying to filter one of object from above json file, Thats I'm trying to this following way.

import React,{ useState, useEffect} from 'react';
import source_data from '../source/data.json';

function CardIntro(props){

    let {selectedItem} = source_data.find(item => item.id == 8);

    return(

            <div> Card Intro  </div>
            <div>{selectedItem.intro}</div>

    )
}

export default CardIntro;

I'm getting the following error, what is missing here

TypeError: Cannot read property 'intro' of undefined

I tried to use .filter also not successful

1
  • find return your object i.e {id:8,intro:"intro_8"} Commented Jan 3, 2021 at 10:17

1 Answer 1

2

There is no selectedItem property in the objects of your array, which is what your code is trying to do with the object destructuring syntax. You probably don't want the destructuring syntax. Just do:

let selectedItem = source_data.find(item => item.id === 8);

Note that you should also change the == into ===. More about strict equality comparison, here. Also bear in mind that your code will not work if the find yields no result. You may want to put up a check against that.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.