Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update the FlatList dynamically in react native?

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={{ paddingBottom: 75 }}

                    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...

like image 995
PvUIDev Avatar asked Nov 20 '25 00:11

PvUIDev


1 Answers

Flatlist will update automatically when you set your state i.e by using this.setState() function, it means whenever any changes made to your state variable it will rerender your flatlist. if you still face the same problem remove your this.state.faqs && part, this looks unnecessary because there is no need to check if you are passing the empty array to faltlist or not, flatlist allows you to pas empty array as well, it will not give you any error.

like image 89
Chandler Bing Avatar answered Nov 21 '25 14:11

Chandler Bing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!