0

I don't want to have a handle refresh function in every single screen in my project, so I created a Helper.js to handle this. This function has this.setState and another call for a function inside the screen component. This is what I got so far but it returns an error.

Exported function

export function handleRefresh(component) {
    const {page, refreshing} = component.state
    component.setState(
      {
        page:1,
        refreshing:true
      },
      () => {
        component.makeRemoteRequest();
      }
    );
  };

and I call it in the component like this:

<FlatList
     ...
     onRefresh={()=> handleRefresh(this)}
     refreshing={this.state.refreshing}
     ...
     />

I saw that you can pass "this" as a param, but the error still says it is undefined.

Prashen
  • 81
  • 7
Mark Kiraly
  • 13
  • 1
  • 4

3 Answers3

0
  1. setState shall be within that screen always where you are using FlatList because after making API you have to update and control the state of that screen.
  2. All the states will be in the component where FlatList using.
  3. Use case are not logical in my view. You can try to create a helper function which accepts different functions params like: page, isRefreshing and return the API response and also the API url and datapost will also be dynamic. Because you want to use it in many areas. It will be difficult to maintain.
  4. So, If you like then use redux what you want.

https://snack.expo.io/@prashen/flatlist-onrefresh

Prashen
  • 81
  • 7
0

You can do in this way.

class AComponent {
    ...
    render() {
        const thisComponent = this;
        <FlatList
         ...
         onRefresh={()=> handleRefresh(thisComponent)}
         refreshing={this.state.refreshing}
         ...
     />
    }
};
Nahrae
  • 63
  • 1
  • 6
0

All this. uses refer a same class or function. Only use IF i'ts a child function, component or method. I'ts don't work out of class function original, you can make a bridge for share data or status. You can use redux for it and using stores for update screen state.

AnderZilla
  • 21
  • 1
  • 10