0

ComponentWillMount has been renamed and deprecated, and is not recommended to be used

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


componentWillMount() {
AsyncStorage.getItem("CART", (err, res) => {
  if (!res) this.setState({ cartItems: [] });
  else this.setState({ cartItems: JSON.parse(res) });
});}

what should I do to fetch the cartItems before rendering ??

Gaurav Roy
  • 11,175
  • 3
  • 24
  • 45
Firas Abu Fares
  • 511
  • 1
  • 6
  • 24
  • This answer can be useful [how-should-i-alternate-componentwillmount](https://stackoverflow.com/questions/52092341/how-should-i-alternate-componentwillmount) – harisu Oct 07 '19 at 12:12

1 Answers1

3

There is a rule of thumb. Does your old code (which implements componentWillMount) performs any side effect? Case no it's just an initialization and you can do it inside constructor. Case you need to perform a side effect (API call for example) you should use componentDidMount instead

state = { cartItems : [] } 

componentDidMount() {
    AsyncStorage.getItem("CART", (err, res) => {
        if (!res) this.setState({ cartItems: [] });
        else this.setState({ cartItems: JSON.parse(res) });
    });
}
Dupocas
  • 20,285
  • 6
  • 38
  • 56
  • and for cases when the component is already mounted, sometimes navigation.navigate doesnt make a fresh new api call , so its better you do navigation.push to make the component realogn itself at top of stack and make fresh new api calls or whatever you want to do inside it. – Gaurav Roy Oct 07 '19 at 12:18
  • Notice, `componentDidMount` it's a great place to fetch **initial** data. If your data must change uppon a `prop / state` update, then you should take a look at `componentDidUpdate` – Dupocas Oct 07 '19 at 12:20
  • correct , but sometimes componentDidUPdate is risky , coz it goes in a loop if not handled properly – Gaurav Roy Oct 07 '19 at 12:21
  • Just in case you have issue with Asyncstorage, place your code in "async" function and use await before Asyncstorage.getItem(), and call this function in ComponentDidMount – Thomas Neveu Oct 07 '19 at 12:26
  • so if i use flatlist and i want to rerender flatlist to get the new data from api i should use componentDidMount? can you give me an example – Firas Abu Fares Oct 07 '19 at 12:27
  • `componentDidMount` to fetch initial data and `componentDidUpdate` to update your data based on a `prop/state` change – Dupocas Oct 07 '19 at 12:29
  • You can use `NavigationEvents` for this purpose if you are using `react-navigation` it will work flawlessly. I was having the same problem of `ComponentDidMount` not being called when I switched between screens so the best way is to use `NavigationEvents`. Use the onWillFocus method. https://reactnavigation.org/docs/en/navigation-events.html – Ammar Ahmed Oct 07 '19 at 19:50