Parma Libera
Parma Libera

Reputation: 166

In React Native i have "WARN Possible Unhandled Promise Rejection (id: 5): TypeError: array.push is not a function"

I ask help for React Native. I have this code:

let historicalCaliberNumCm = await AsyncStorage.getItem('@historicalCaliberNum');
console.log(historicalCaliberNumCm);
console.log(this.state.cm);
historicalCaliberNumCm.push(this.state.cm);

This is the result:

[Tue Jan 05 2021 23:48:50.330]  LOG      [0.992872416250891]
[Tue Jan 05 2021 23:48:50.332]  LOG      0.3682160866743222
[Tue Jan 05 2021 23:48:50.461]  WARN     Possible Unhandled Promise Rejection (id: 5):
TypeError: _historicalCaliberNumCm2.push is not a function. (In '_historicalCaliberNumCm2.push(_this2.state.cm)', '_historicalCaliberNumCm2.push' is undefined)

Can anyone help me?

Upvotes: 0

Views: 495

Answers (2)

proton
proton

Reputation: 341

AsyncStorage stores strings only. Please check docs: https://reactnative.dev/docs/asyncstorage

There's no guarantee that item under specified key exists. You should check if it's not null first. Then if it's not, you have to parse string into an object. For example you can use JSON.parse(historicalCaliberNumCm). Then if result is an array, you can push into it additional data.

Upvotes: 0

Samuli Hakoniemi
Samuli Hakoniemi

Reputation: 19059

AsyncStorage.getItem returns a string, not an array, hence you can't use .push() which is a function for an array. You should use, e.g. JSON.parse(historicalCaliberNumCm); first to convert that string into an array.

Upvotes: 1

Related Questions