简体   繁体   中英

Correct way to setState in React when item in state is not a collection

I'm working with realtime financial data such as equities and precious metal prices. I'm hitting an API every few seconds to grab the latest price for a given asset and storing that price in state. However, I've always updated state with an array or array of objects, but this data is just a string. If the latest GET request returns a different value than what is currently set then overwrite the value.

I'm just wondering what best practices are for updating a simple string in state?

my state constructor:

this.state = {
  goldPrice: '',
  items: {}
}

My API request:

fetchGoldPrice() {
  jQuery.ajax({
    method: 'GET',
    headers: {'Access-Control-Allow-Origin': '*'},
    url: Constants.API_URL,
    success: (gold) => {
      this.updateGoldPrice(gold.gold_bid_usd_toz);
    }
  });
}

If successful the fetch calls updateGoldPrice and passes in the price that was returned.

updateGoldPrice(goldPrice) {
  this.setState({ goldPrice: goldPrice });
}

And then I check the price every 30 seconds:

componentDidMount() {
  this.fetchGoldPrice();
  this.timer = setInterval(
    () => this.fetchGoldPrice(), 30000);
}

I'm just curious if this is an alright way to do this. Because everything I read says to do something like this:

addItem(item) {
  const items = {...this.state.items};
  items[item] = item;
  this.setState({ items: items });
}

But I'm not storing all the prices in an array, I just want the single latest price.

Thank you.

Well the best practice you are referring to is Never mutate the state! .
In your case, string is a primitive type (primitive value actually), thus its already immutable by default so no worries here.
You need to look out from reference types like Array & Object .

Primitive Types (6 as of ES6 ):

Boolean
Null
Undefined
Number
String
Symbol (new in ECMAScript 6)

You are doing this correctly. Your UI only displays the latest price so that's all you need to store in your state. No need to store historical prices if you're not displaying them.

Furthermore, storing primitive types in your state this.setState({foo: "bar"}) is completely fine.

The recommended way as per react documentation is to use the setState method from the react libray.. using this method . is by "setState({MyStateToModify: "new value"}). Hope that can help you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM