Alireza Valizade Alireza Valizade - 15 days ago 5
React JSX Question

How to call setState in react from a function

I have a method in my React class, but because I want to use that in several classes in my app, I converted that to a separate function. Now my problem is that in this function I use

this.setState()
and want to
setState
in my classes. How can I call
setState()
from a function?

This is my function :

export const syncBasketItemsWithServer = (categoriesData, lBasketItem) => {
if (categoriesData.has_sub_category) {
categoriesData.categories.map((item, index)=> {
syncBasketItemsWithServer(item, lBasketItem);
});
}
if (categoriesData.category_items) {
const exist = _.findWhere(categoriesData.category_items, {uid: lBasketItem.uid});
if (exist) {
lBasketItem.price = exist.price ? exist.price : categoriesData.price;
this.setState({
arr: this.state.arr.concat([lBasketItem])
});
}
}
};

Answer

I Try This :

  import _ from 'underscore';
    export function syncBasketItemsWithServer(categoriesData, lBasketItem) {
      if (categoriesData.has_sub_category) {
        categoriesData.categories.map((item, index)=> {
          //bind again
          syncBasketItemsWithServer.call(this, item, lBasketItem);
        });
      }
      if (categoriesData.category_items) {
        const exist = _.findWhere(categoriesData.category_items, {uid: lBasketItem.uid});
        if (exist) {
          lBasketItem.price = exist.price ? exist.price : categoriesData.price;
          this.setState({
            syncedItems: this.state.syncedItems.concat([lBasketItem])
          });
        }
      }
    }