0

i'm using the tab view react native library to build a user account screen. my request is simple, how can i update the tab view content after an api call that fetches the user data?

function UserStoreScreen({ navigation, route }) {
  const layout = useWindowDimensions();
  const [index, setIndex] = React.useState(0);
  const [userStore, setUserStore] = React.useState({});
  const [routes] = React.useState([
    { key: "first", title: "Dressing" },
    { key: "second", title: "À propos" },
  ]);
  const user = route.params;

  // renders undefined 
  const FirstRoute = () => (
    <>
      <View style={styles.userContainer}>
        <ListItem
          image={`${IMAGES_BASE_URL}${userStore.photo}`}
          title={`${userStore.username}`}
          subTitle={`${userStore.store.length} Articles`}
        />
      </View>
    </>
  );

  const SecondRoute = () => (
    <>
      <View style={{ flex: 1, backgroundColor: "#ff4081" }} />
    </>
  );

  const renderScene = SceneMap({
    first: FirstRoute,
    second: SecondRoute,
  });

  const getUser = async () => {
    await axiosApi
      .post("/getUserProducts", { user_id: user.user_id })
      .then((response) => {
       // didn't work since set state is async 
        setUserStore(response.data);
        
      })
      .catch((err) => {
        console.log(err);
      });
  };
  // Get store products
  useEffect(() => {
    getUser();
  }, []);

  return (
    <Screen style={styles.screen}>
      <TabView
        navigationState={{ index, routes }}
        renderScene={renderScene}
        onIndexChange={setIndex}
        initialLayout={{ width: layout.width }}
      />
    </Screen>
  );
}

is there a way to make the content of the tab view updated after i receive the data from the api call?

Sb Zakaria
  • 311
  • 6
  • 18
  • You can check this answer: https://stackoverflow.com/questions/55552936/expo-react-native-tabview-re-render-component-tab-on-state-change – Michael Harley Jul 05 '22 at 12:10

1 Answers1

0

Yes, there is a way to forcefully re-mount a component. To do that, we can use key props like this:

return (
    <Screen style={styles.screen}>
      <TabView
        key={JSON.stringify(userStore)}
        navigationState={{ index, routes }}
        renderScene={renderScene}
        onIndexChange={setIndex}
        initialLayout={{ width: layout.width }}
      />
    </Screen>
  );

How does key props work? Every time a component is re-rendering, it will check whether the key value is the same or not. If it's not the same, then force a component to re-render.

In this case we will always check if userStore value has changed or not.

Michael Harley
  • 831
  • 1
  • 9
  • 20