0

Is it possible to set the state with the switch instruction in the manner given below? Or maybe none of these ways is a good solution

Can I set:

return this.setState({
         stat1: 'a'
       })

or

return this.state.stat1 = 'a'

First way

    books = (price) => {
      switch(price) {
        case 100:
          return this.setState({
            stat1: 'a'
          })
        case 1000:
          return this.setState({
            stat1: 'b'
          })
        case 2000:
          return this.setState({
            stat1: 'c'
          })
        default:
          return this.setState({
            stat1: ''
          })
      }
    }

Second way

    books = (price) => {
      switch(price) {
        case 100:
          return this.state.stat1 = 'a'   
        case 1000:
          return this.state.stat1 = 'b'
        case 2000:
          return this.state.stat1 = 'c'
        default:
          return this.state.stat1 = ''
      }
    }
Umbro
  • 1,984
  • 12
  • 40
  • 99

5 Answers5

2

well u can use first way but this how u can do it also:

const books = price => {
this.setState({
  stat1: price===100?"a"
        :price===1000?"b"
        :price===2000?"c"
        :null
   })
 }

second way is wrong check this for explanation Why we can't change states in react without calling setState()

adel
  • 3,436
  • 1
  • 7
  • 20
  • Maybe? --> `books = price => { this.setState({ stat1: price===100?"a": price===1000?"b": price===2000?"c": ' ' }) }` – Umbro Jun 28 '19 at 08:25
  • @umbro forgot to add last else check answer now! it should work! – adel Jun 28 '19 at 08:36
0

Since React state should be treated as immutable, you shouldn't set state by assigning a new value directly (i.e. this.state.stat1 = 'a'). So only the first way you provided works.

However, the setState setter does not have an explicit return value. As a result, the value of books will always be undefined.

Claire Lin
  • 2,372
  • 8
  • 13
0

Your "First way" should work. Because you cant assign values to e state like solution 2

Nicola Munz
  • 73
  • 14
0

We can not use this way.

return this.state.stat1 = 'a'

it will not render after state is updated and that's why we will not able see the change on the screen. we need to use the setState() method only. and I think you should try to use Async/ await it might help, 1st try without it and then try with async/await.

books = async (price) => {
      switch(price) {
        case 100:
          return await this.setState({
            stat1: 'a'
          })
        case 1000:
          return await this.setState({
            stat1: 'b'
          })
        case 2000:
          return await this.setState({
            stat1: 'c'
          })
      }
    }
0

You can use this

setPrice = (price) => {
    this.setState(() => ({ stat1: ({100: "a", 1000: "b", 2000: "c"})[price] }))
}
Tolotra Raharison
  • 3,034
  • 1
  • 10
  • 15