0

I'm trying to show time in a react app and want to display it in a 12-hour format.

I've written a function to remove '12' if the hours show 13 and over. I want to pass that function into setState but continue to get a syntax error.

setTimeDate() {
    const hours = currentDate.getHours()
    const min = currentDate.getMinutes()
    this.setState(formattedHours(prevState, this.props) {  
      time: `${hours}:${min}`
      }
    )
  }

formattedHours() {
  if(hours > 13) {
    afternoonHours = `${(hours - 12)} "PM"`
  } else {
    morningHours = `${hours} "AM"`
    }
 }

render() {
    const { time } = this.state
    return (
      <div className="showTime">
        { time }
      </div>
    )
  }

I expected to see 1:31 PM but am simply getting a syntax error in my setState line. I am unable to get past that.

In addition to this, how do I pass in the previous state?

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
  • 6
    Why do you need a function for that update? You already have the hours and minutes computed, just call ```setState({ time: `${hours}:${min}` })``` directly instead of over-complicating your code? Although I would recommend not turning it into a string - do that in `render()` using `const { hours, mins } = this.state.time` and `
    { formTimePrint(hours, mins) }
    `, and a setState call that's `setState({ time: { hours, min }})`. Don't turn data into strings until the moment you need them shown to a reader.
    – Mike 'Pomax' Kamermans Jun 30 '19 at 15:04
  • Your formatted hours function doesn't return a value – Mark Jun 30 '19 at 15:21

1 Answers1

0

To pass the previous state you can use a life cycle method componentDidUpdate(prevProps, prevState) which receives prevState and prevProps as parameters so you can access them here.

Aman-D
  • 71
  • 3