Hammad Hassan
Hammad Hassan

Reputation: 622

How to pass state within state in react native

I want to pass my data array and favorites array which both I am setting in states. I want to pass my favorites array state in my data state. How can I achieve that?? My code looks like this

 class Favorites extends Component {
  constructor(props) {
    super(props);
    this.state = {
      favorites: [],
      data: [],

    };
  }

 axios
      .post(
        'http://staging.islamicmedia.com.au/wp-json/islamic-media/v1/user/media/library',
        data,
      )
      .then((res) => {
        console.log(res.data);

        this.setState({
          data: res.data,

          favorites: res.data.data.favorite.filter((val) => val != null),
        });
      });
  };

Upvotes: 0

Views: 162

Answers (1)

Carlos Saiz Orteu
Carlos Saiz Orteu

Reputation: 1805

You should do that axios call in the componentDidMount:

class Favorites extends Component {
  constructor(props) {
    super(props);
    this.state = {
      favorites: [],
      data: [],

    };
  }
componentDidMount() {

 axios
      .post(
        'http://staging.islamicmedia.com.au/wp-json/islamic-media/v1/user/media/library',
        data,
      )
      .then((res) => {
        const favs = res.data.data.favorite.filter((val) => val !== null);

        this.setState({
          data: res.data,
          favorites: favs
        });
      });
  };
}

Upvotes: 2

Related Questions