Reputation: 83
I have class component functions that handle a search function.
filterData(offers,searchKey){
const result = offers.filter((offer) =>
offer.value.toLowerCase().includes(searchKey)||
offer.expiryDate.toLowerCase().includes(searchKey)||
offer.quantity.toLowerCase().includes(searchKey)
)
this.setState({offers:result})
}
const handleSearchArea = (e) =>{
const searchKey=e.currentTarget.value;
axios.get(`/viewPendingSellerOffers`).then(res=>{
if(res.data.success){
this.filterData(res.data.existingOffers,searchKey)
}
});
}
Now I try to convert these class component functions to functional component functions. To do this I tried this way.
const filterData = (offers,searchKey) => {
const result = offers.filter((offer) =>
offer.value.toLowerCase().includes(searchKey)||
offer.expiryDate.toLowerCase().includes(searchKey)||
offer.quantity.toLowerCase().includes(searchKey)
)
setState({offers:result})
}
const handleSearchArea = (e) =>{
const searchKey=e.currentTarget.value;
axios.get(`/viewPendingSellerOffers`).then(res=>{
if(res.data.success){
filterData(res.data.existingOffers,searchKey)
}
});
}
But I get an error that says "'setState' is not defined". How do I solve this issue?
Upvotes: 0
Views: 37
Reputation: 251
Solution:
import React, {useState} from "react";
import axios from "axios";
const YourFunctionalComponent = (props) => {
const [offers, setOffers] = useState()
const filterData = (offersPara, searchKey) => {// I changed the params from offers to offersPara because our state called offers
const result = offersPara.filter(
(offer) =>
offer?.value.toLowerCase().includes(searchKey) ||
offer?.expiryDate.toLowerCase().includes(searchKey) ||
offer?.quantity.toLowerCase().includes(searchKey)
);
setOffers(result);
};
const handleSearchArea = (e) => {
const searchKey = e.currentTarget.value;
axios.get(`/viewPendingSellerOffers`).then((res) => {
if (res?.data?.success) {
filterData(res?.data?.existingOffers, searchKey);
}
});
};
return (
//To use your *offers* state object just call it like this {offers?.El1?.El2}
);
};
export default YourFunctionalComponent;
Note: It is recommended to do null check before accessing nested objects like this res?.data?.existingOffers
, Optional chaining will help us in this regard.
Upvotes: 1