waze
waze

Reputation: 527

React-Native update AsyncStorage item

My app send a notification to the user everytime a car changes price. It is done with code that runs every hour.

Code is the following:

  backgroundData(){
      BackgroundTimer.setInterval(() => {

        AsyncStorage.getItem('key').then(JSON.parse).then(items => {
          this.setState({value: items});
        })

        if(!this.state.value == 0 || !this.state.value == null){
          const promises = this.state.value.map((item, index) =>
            fetch(`URL/GetDetalhesViatura?CarID=${item[0]}`)
             .then(response => response.json())
          )
          Promise.all(promises).then(viaturas => this.setState({viaturas: flatten(viaturas)}))

          const newItem = []
          this.state.viaturas.map((item, index) =>
            newItem.push([item.Preco, item.CodViatura]),
            this.setState({ stateArray: newItem })
          )

          const newItem2 = []
          this.state.value.map((item, index) =>
            newItem2.push([item[1], item[0]]),
            this.setState({stateArray2: newItem2})
          )

          var results = new Array();
          //CODE TO CHECK ARRAYS FOR DIFFERENT PRICES
          this.setState({results: results})

          if(!this.state.results == 0 || !this.state.results == null){
            const promises = this.state.results.map((item, index) =>
              fetch(`URL/GetDetalhesViatura?CarID=${item[1]}`)
               .then(response => response.json())
            )
            Promise.all(promises).then(viaturas2 => this.setState({viaturas2: flatten(viaturas2)}))

            this.state.viaturas2.map((item, index) =>
              PushNotification.localNotification({
                message: "Notification",
              })
            )
          }
        } else {
          console.log('empty')
        }
      }, 9999999);
  }

First it fetchs the current data on my AsyncStorage. If it has data, it fetches the new data from the API, and after that compares both datas and if there are different prices it sends a notification to the user.

The problem is that I need to update the 'key' for each car (if the price changed) with the new price, or the app will keep sending notifications to the user.

Upvotes: 1

Views: 2350

Answers (1)

waze
waze

Reputation: 527

I couldn't get what I wanted with AsyncStorage, so I had to use a wrapper called simple-store: https://github.com/jasonmerino/react-native-simple-store

I had to change alot of code, but then I was able to change the data I wanted and save it.

With simple-store, it saves each car on an individual array or object in the same key, which was alot easier to manipulate data.

Upvotes: 2

Related Questions