Initially loading data from API to FlatList using setState and it loaded perfectly. But I have to perform some actions like create, update & delete of FlatList row. When I try to add new data to the FlatList, the data is not rendered in FlatList with an updated one, but In API it's updated.
How to re-render the flatlist after updating to the API and load the new data to FLatList?
Here is my code:
constructor(props) {
super(props);
this.state = {
faqs: [],
}
this.loadFaq();
};
To load the data to FlatList from the API:
loadFaq = async () => {
let resp = await this.props.getFaqGroup();
if (resp.faqs) {
console.log(resp.faqs)
this.setState({
faqs: resp.faqs,
// refresh: !this.state.refresh
})
}
};
To add new data to API:
createFaqGroup = async (name) => {
let resp = await this.props.createFaqGroup(name);
// console.log("resp", resp)
// this.setState({
// refresh: !this.state.refresh
// })
// this.forceUpdate();
this.closePanel();
}
FlatList code:
{this.state.faqs && <FlatList
extraData={this.state.faqs}
horizontal={false}
data={this.state.faqs}
contentContainerStyle=
renderItem={({ item: faqs }) => {
return <Card gotoQuestionList={this.gotoQuestionList} key={faqs._id} faqs={faqs} openPanel={(selectedFaq) => this.openPanel({ name: selectedFaq.name, id: selectedFaq._id })} deletePanel={(selectedFaq) => this.deletePanel({ name: selectedFaq.name, id: selectedFaq._id, isPublished: selectedFaq.isPublished })}></Card>
}
}
keyExtractor={(item) => item._id}
/>}
this.props.createFaqGroup function code:
export const createFaqGroup = (name) => {
const options = {
method: 'POST',
data: { "name": name },
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${store.getState().auth.info.token}`
}
};
return async (dispatch) => {
console.log('url::', options)
try {
let url = `${config.baseUrl}${config.faqUrl}`;
let resp = await axios(url, options);
console.log(resp.data)
return resp && resp.data ? resp.data : null;
} catch (error) {
alert(error)
if (error.response && error.response.status === 401) {
dispatch({
type: type.ERROR,
data: error.response.data
});
} else {
dispatch({
type: type.CREATE_FAQ_GROUP_ERROR,
error: error.message
});
}
}
};
}
Any help much appreciated pls...
from How to update the FlatList dynamically in react native?
No comments:
Post a Comment