Search code examples
react-nativereact-reduxreact-props

How can i get token in componentDidMount from redux?


I'm trying to add a props inside a componentDidMount from redux. If i try to log in in to my app with componentDidUpdate i'm able to see the data loaded, but if i close the app and after i try to re open it, i can't see the data.

class Profile extends Component {

constructor(props) {
    super(props);
    this.state = {
      results: []
    };
  }

componentDidUpdate = () => {
    this.getMyWeather();
};

getMyWeather = () => {
    const {
      getUser: { userDetails }
    } = this.props;
    axios
      .get(
        settings.host +
          'my_api_url',
        {
          headers: { Authorization: 'Token ' + userDetails.token },
        }
      )
      .then(({ data }) => {
        this.setState({
          results: data.results
        });
      })
      .catch(error => alert(error));
  };

render() {
    return (
      <View style={styles.container}>
        {this.state.results &&
          this.state.results.map((data, index) => (
            <Text key={index}>{data.title}</Text>
          ))}
      </View>
    );
  }
}

let mapStateToProps;
mapStateToProps = state => ({
  getUser: state.userReducer.getUser
});

let mapDispatchToProps;
mapDispatchToProps = dispatch => ({
  dispatch
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Profile);

How i can fetch the data also after closing and re-open the app?


Solution

  • Try this way

    async componentDidMount() {
        // GET request using axios with async/await
        const {userDetails} = this.props.getUser; <-- Try this way -->
        const data = await this.getMyWeather(userDetails);
        this.setState({
              results: data
        });
    }
    
    getMyWeather = async (userDetails) => {
        await axios
          .get(
            settings.host +
              'my_api_url',
            {
              headers: { Authorization: 'Token ' + userDetails.token },
            }
          )
          .then(({ data }) => {
            return data.results;
          })
          .catch(error => alert(error));
    };