Can someone please help on updating the response data on click of list item. So there is a list of products being binded in <li>. When the user clicks on any of the list item, the value will be added as a keyword in API and data will be rendered accordingly
class SearchFilter extends Component {
constructor(props) {
super(props);
this.state = {
sidefilterbyProductData: [],
sidefiltersbyContentType: [],
featuredData: [],
resourceData: [],
othersData: [],
error: false,
};
}
componentDidMount() {
axios
.getAll()
.then((response) => {
this.setState({
sidefilterbyProductData: response.data.data.filter_by[1].input_list,
sidefiltersbyContentType: response.data.data.filter_by[0].input_list,
featuredData: response.data.data.primary_data,
resourceData: response.data.data.resources,
othersData: response.data.data.others,
});
})
.catch((error) => {
this.setState({
error: true,
});
});
}
handleonClick = () => {
axios.get(`${this.key}`)
.then((response) => {
this.setState({
featuredData: response.data.data.primary_data,
resourceData: response.data.data.resources,
othersData: response.data.data.others,
});
})
.catch((error) => {
this.setState({
error: true,
});
});
}
render() {
return <div><h3>Filter by product</h3>
<ul>
{Object.keys(this.state.sidefilterbyProductData).map((key, i) => (
<li key={key}><a onClick={this.handleonClick()}>{this.state.sidefilterbyProductData[key]}</a></li>
))}
</ul></div>;
}
First, it's not clearly what is your problem, if is about a logic to implement it, or, it's a bug or something else...be welcome to complement your question if you want.
So, let's go.
I usually don't work components like this as class components, however, analyzing your code, you could add a parameter on handleonClick function, something like:
class SearchFilter extends Component {
constructor(props) {
super(props);
this.state = {
sidefilterbyProductData: [],
sidefiltersbyContentType: [],
featuredData: [],
resourceData: [],
othersData: [],
error: false,
};
}
componentDidMount() {
// Is it needed ?
}
searchInApi = async (search:string): Promise<Foo[]> => {
const response = await axios.get("/api/v1/products", {
withCredentials: true,
params: [
'search' : search
]
});
return response.data;
}
handleonClick = (search:string): => {
searchInApi(search)
.then((response) => {
this.setState({
featuredData: response.data.data.primary_data,
resourceData: response.data.data.resources,
othersData: response.data.data.others,
});
})
.catch((error) => {
this.setState({
error: true,
});
});
}
render() {
return (
<div>
<h3>Filter by product</h3>
<ul>
{Object.keys(this.state.sidefilterbyProductData).map((key, i) => (
<li key={key}><a onClick={this.handleonClick()}>{this.state.sidefilterbyProductData[key]}</a></li>
))}
</ul>
</div>
);
}
}
You can separate responsibilities dividing your code into two components, one will contain the search in API logic and the other one that will render your front-end components.