Nothing happens when I click on the reset button. I am lost as to how to fix this, do you guys have any insights? Thank you! Please let me know if I need to add anymore information. I am trying to get it to where I can click sort and then reset back to the original display. Thank you so much in advance!
const ToyList = (props) => {
const [sortedToys, setSortedToys] = useState(false)
const dispatch = useDispatch()
// imitates componentdidmount because it runs right away as soon as the component loads
useEffect(() => {
dispatch(fetchToys())
},[dispatch])
const sortToys = (toys) => {
if (sortedToys === true) {
return toys.sort( (toyA, toyB) => toyA.name.localeCompare(toyB.name))
}
if (sortedToys === false) {
return toys
} else {
return toys }}
function HandleSortOptionChange() {
setSortedToys(true)
}
function HandleSortOptionChangeFalse(e) {
setSortedToys(false)
}
return (
<div>
<div className="sortDiv">
<Button className="m-3" value="toy" onClick={HandleSortOptionChange}>Toys A-Z</Button>
<Button className="m-3" value="toy" onClick={HandleSortOptionChangeFalse}>Reset</Button>
</div>
<div>
</div>
{props.toys ? sortToys(props.toys).map(toy =>
<Container fluid>
<Row>
<Col key={toy.id}>
<Card style={{ width: '17rem' }} className='text-center'>
<Link to={`/toys/${toy.id}`}>{toy.name}
<Card.Img variant='top' src={toy.image_url} alt="toyimage" width="300" height="300" /></Link>
</Card>
</Col>
</Row>
</Container>
)
: <h2> Loading </h2>}
</div>
)
}
const mapStateToProps = (state) =>
({ toys: state.toys })
export default connect(mapStateToProps, {fetchToys})(ToyList)
CodePudding user response:
.sort mutates the original array so if sortedToys was ever set to true, the original toys array is always sorted so even if you return toys when false it will still be sorted.
CodePudding user response:
You shouldn't need sortToys and it really is best to have the component return the JSX; here is a reformatted way where you wouldn't need this dispatch and can take use of useEffect on the toys state itself.
const ToyList = (props) => {
const [toys, setToys] = useState([]);
const [sortToys, setSortToys] = useState(false);
const [startingToys, setStartingToys] = useState([]);
// On launch we can save the inital order to state
useEffect(() => {
// Set the toys
setToys(fetchToys());
// Save this ordering
setStartingToys(toys);
}, []);
// Whenever sortToys changes, we can also change toys
// thus re-rendering the list in the order you want
useEffect(() => {
if (sortToys) {
setToys(toys.sort((a, b) => a.name.localCompare(b.name)));
} else {
setToys(startingToys);
}
}, [sortToys]);
// Function to change the sort
const handleSortChange = () => setSortToys(() => !sortToys);
return (
<>
{/* Your JSX Here */}
</>
);
}