Trying to create a filter that'll return items depending on some property(inStock in this case)
I'm not getting any items when trying to set the filter to filter only items who have true in their inStock property , at all.
when console.log availability - i'm getting the proper boolean i set on the filter (true/false) and when i console.log the the inStock items they all return true (which is fine, it's what i set).
I have tried setting the value in the filter component as a string- still didn't work.
would much appreciate your help with this one
toy.service.js
function query(filterBy) {
return storageService.query(STORAGE_KEY).then((toys) => _filteredToys(toys, filterBy));
}
function _filteredToys(toys, filterBy) {
const { txt, availability } = filterBy;
const filteredtoys = toys.filter((toy) => {
console.log(availability);
console.log(toy.inStock);
return toy.inStock === availability;
});
return Promise.resolve(filteredtoys);
}
the toy-filter component
import React from 'react';
export class ToyFilter extends React.Component {
state = {
filterBy: {
availability: '',
txt: '',
},
};
handleChange = ({ target }) => {
const { name, value } = target;
this.setState(
(prevState) => ({ filterBy: { ...prevState.filterBy, [name]: value } }),
() => {
this.props.onSetFilter(this.state.filterBy);
}
);
};
render() {
const { txt } = this.state.filterBy;
return (
<section>
<select name='availability' onChange={this.handleChange}>
<option value='' key='filter-all'>
All
</option>
<option value={true} key='filter-in-stock'>
in stock
</option>
<option value={false} key='filter-sold-out'>
sold out
</option>
</select>
<input type='text' name='txt' value={txt} onChange={this.handleChange} placeholder='Search toy...' />
</section>
);
}
}
The way in which you are setting availability in the state, it will always be a string. So true in the console output is not a boolean but a string. Please check the data type of availability using typeof availability.
My guess is comparison return toy.inStock === availability is failing because inStock is bool while availability is string.