Redux state change but the component don't re render whene I back to the screen

312 Views Asked by At

I have two screens, A and B. both of them uses the same global state

<Text style={Styles.textScoreHeader}>{this.props.profleInfos.Points}</Text>

using this :

const mapStateToProps = (state) => {
  return {
    folder: state.account.folder,
    theme: state.account.theme,
    whichAccount: state.account.whichAccount,
    profleInfos: state.account.profleInfos,
  };
};
export default connect(mapStateToProps)(ScreenA);

for screen A and :

const mapStateToProps = (state) => {
  return {
    folder: state.account.folder,
    theme: state.account.theme,
    whichAccount: state.account.whichAccount,
    profleInfos: state.account.profleInfos,
  };
};
export default connect(mapStateToProps)(ScreenB);

for screen B.

In screen A I click a button to go to screen B where I change the profleInfos.Points global state like this:

_Transaction(folder, apiName, code) {
  Transaction(folder, apiName, code).then(data => {
    if (data.success) {
      var theProfleInfos = this.props.profleInfos 
      theProfleInfos.Points = data.LoyPoints //changing profleInfos.Points
      const actionProfileInfos = { type: "SET_PROFILE_INFOS", value: theProfleInfos }
      this.props.dispatch(actionProfileInfos) // dispatch the action
    }
    this.setState({ scanningResponse: data, isLoading: false })
  })
};

I use this.props.dispatch(actionProfileInfos) instead of mapdispatchtoprops (tell me if I have to do it, but I prefer this method).
In this screen (B) I display the this.props.profleInfos.Points and it works fine (the value changes after scanning) but when I go back to the screen A (back button) the this.props.profleInfos.Points doesn't refresh.

PS. I have the same value in the drawer, if I open drawer I can see the change in the same value, maybe because I 'open' the drawer

1

There are 1 best solutions below

0
On BEST ANSWER

I was able to solve the problem with useFocusEffect in screen A : this link helped me see the class component part

This is my code:

   import { useFocusEffect } from '@react-navigation/native';

function Reloader({ api }) {
  useFocusEffect(
    React.useCallback(() => {
      api();
    }, [])
  );
  return null;
}

// ...

class ScreenA extends React.Component {
  // ...

  _getProfileInfo(folder, apiName, LoyPhone, LoyRef, LoyCardNum) {
    getPeintreInfo(folder, apiName, LoyPhone, LoyRef, LoyCardNum).then(data => {
      const actionProfileInfos = { type: "SET_PROFILE_INFOS", value: data }
      this.props.dispatch(actionProfileInfos)
    })
  }

  render() {
    return (
        <>
        <Reloader
          api={() => this._getProfileInfo(this.props.folder, 'GetProfileInfos.php', 'empty', 1, 'empty') />
            {/* rest of ScreenA component */ }
        </>
      );
    }
  }