I’m confused why this isn’t working. I can do an API fetch, and filter the data just fine. But, the parent component already has fetched this data, so I need to use it without doing another call.
Parent Component:(I want to filter the data set in contacts
in a child of this component)
class Database extends Component {
constructor(props){
super(props);
this.state = {
clients: [],
contacts: []
}
}
I pass the contacts
array of objects to the child component like so:
<Container className="database">
{this.state.clients.map(client => (
<ClientCard
key={client.id}
short={client.short}
client={client.client}
{...this.state}
/>
))}
</Container>
Then in my child component, I am filtering the contacts
data for use in my child component, so I have a beginning state of:
class ClientCard extends Component {
constructor(props){
super(props);
this.state = {
showHide: false,
filteredContacts: []
}
So what I would like to do now, is upon componentDidMount
, filter the props data like so:
this.setState({
filteredContacts: this.props.contacts.filter(contact => this.props.contacts.short === this.props.short)
});
I’m not getting any errors, but it’s also not setting the state of filteredContacts
as needed either. The short
mentioned in the code is an abbreviation for the clients stored in the array as an object property I’m using to help me filter.
You need to use the
contact
passed down to the filter function in order to filter the contacts in that array. Presumably eachcontact
holds ashort
property to which you want to compare it against the propshort
of the component.There shouldn’t be a
this.props.contacts.short
sincethis.props.contacts
is an array.