Talya Sterman
Talya Sterman

Reputation: 215

Utility function that uses the store

I am working with react and I need to create a utility function that uses a parameter from the redux store.

What is the correct way to implement the function?

TIA

Ill give my case as an example: I need a function the receives a zonedTimeOffset from the redux store and return UTC time with the offset (the zoned time). I will use this function from various components throughout my App

Upvotes: 1

Views: 844

Answers (2)

Talya Sterman
Talya Sterman

Reputation: 215

I worked around this by using the useSelector in the FC that calls the utility function and pass into the utility function the zoned Offset. Thank you all for your help

Upvotes: 1

Nicky McCurdy
Nicky McCurdy

Reputation: 19573

Since you're using React Redux's useSelector to access the store, you can write a custom hook that calls it:

function useTimeZone(date: Date) {
  const zonedTimeOffset = useSelector(state => state.zonedTimeOffset)
  return new Date(date.getDate() + zonedTimeOffset)
}

Then you can call useTimeZone in any component (or any other custom hook) instead of useSelector:

const dateWithTimeZone = useTimeZone(new Date())

Upvotes: 2

Related Questions