Maintaining the "Date" value in React Native DatePickerIOS when returning from other pages

In my scenario, I am using the DatePickerIOS component. The example in the documentation initializes a new Date() and uses state to store and update the Date value. However, when navigating to another page and returning, the time changes and I find myself needing to reset this value.

This is how the document suggests using the component:

static defaultProps = {
    date: new Date()
    timeZoneOffsetInHours: (-1) * (new Date()).getTimezoneOffset() / 60,
};

state = {
    date: this.props.date,
    timeZoneOffsetInHours: this.props.timeZoneOffsetInHours,
};

onDateChange(date) {
    this.setState({date: date});
};

render(){
    return(
            <View style={styles.wrap}>
                <View style={styles.datePickerIOS}>
                    <DatePickerIOS
                        date={this.state.date}
                        mode="time"
                        timeZoneOffsetInMinutes={this.state.timeZoneOffsetInHours * 60}
                        onDateChange={this.onDateChange.bind(this)}
                        minuteInterval={10}
                    />
                </View>

I attempted to use props and save this data to local storage.

static defaultProps = {
    date: new Date()
    timeZoneOffsetInHours: (-1) * (new Date()).getTimezoneOffset() / 60,
};

state = {
    date: this.props.date,
    timeZoneOffsetInHours: this.props.timeZoneOffsetInHours,
};

componentWillMout() {
    this.props.updateDate(this.props.date)
}

onDateChange(date) {
    this.setState({date: date});
    this.props.updateDate(date)
};

render(){
    return(
            <View style={styles.wrap}>
                <View style={styles.datePickerIOS}>
                    <DatePickerIOS
                        date={this.props.alarmConfig.date}
                        mode="time"
                        timeZoneOffsetInMinutes={this.state.timeZoneOffsetInHours * 60}
                        onDateChange={this.onDateChange.bind(this)}
                        minuteInterval={10}
                    />
                </View>

The function updateDate(date) is an action:

export function updateDate(date){
return {
    type: "UPDATE_DATE",
    date: date,
    }
}

export function alarmConfig(state=initialState, action){
switch(action.type) {
    case types.UPDATE_DATE:
        return {
            ...state,
            date: action.date
        };

When following this approach, the value under alarmConfig.date turns into a string, resulting in an error as the DatePickerIOS Date prop requires a Date type.

If I simply make the change below:

<DatePickerIOS
      date={this.state.date}
      mode="time"
      timeZoneOffsetInMinutes={this.state.timeZoneOffsetInHours * 60}
      onDateChange={this.onDateChange.bind(this)}
      minuteInterval={10}
 />

Both the value under alarmConfig.date and state.date become Dates again.

What could be causing this situation? And how can I modify the code to achieve my goal?

I appreciate everyone's input.

Answer №1

  • Assuming you are storing the date in your Redux store based on the code snippet provided above, it is recommended to map the application state to your component's props using the mapStateToProps function.

Refer to: http://redux.js.org/docs/basics/UsageWithReact.html#implementing-container-components

  • It is possible to store a Date object in your Redux store, so the error message "alarmConfig.date is a string" could be due to the initial state setup. Can you provide more information about how your initialState variable is defined?

  • If you still need to serialize the Date as a String, consider using the library available at momentjs.com.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing AJAX for showcasing the data from an XML document

Our professor gave a brief explanation of AJAX, expecting us to showcase the data from an XML file in a scrollable text area on our website. Unfortunately, I am facing issues with loading the XML file into the designated div area. Any assistance or suggest ...

Protractor encounters a TypeError when attempting to navigate with Firefox version 59 due to a cyclic object value

Our team has implemented several Protractor tests for our Angular JS application. Recently, we considered upgrading the Firefox browser to version 59 while using Selenium 3.11.0. However, after the upgrade, whenever we try to use element(by. in our tests ...

Attempting to send a Promise to another function for it to return, encountering an error of "Unhandled promise rejection"

My goal is to develop a versatile database update function that can be utilized for creating more customized update functions. Within the module database.js, the following code is present: const {Pool,Client}=require('pg'); const pool=new Pool( ...

Determine the presence of a JSON object within a file using JavaScript

Currently, I am developing a mobile app using react-native and have been facing challenges implementing error checking. To store data retrieved from an API in JSON format, I am employing redux along with thunk. At times, the search results yield a JSON res ...

How to style text in CSS with a numbered underline beneath

Is there a way to apply underlining to text and include a small number underneath the underline in a similar style shown in this image, by utilizing css, html, or javascript? ...

Step-by-step guide on dynamically fetching additional images from a directory using php, jquery, and ajax

I have a scenario where I have multiple folders, each containing up to 20 images. On my HTML page, I want to display the first 5 images and provide a "click to view more" option to show the remaining 15 images when clicked. Currently, the issue I am facin ...

Firebase onSnapshot error when retrieving data from Snapchot

Having trouble with Firebase authentication. Whenever I try to authenticate with Firebase, I encounter this error message: App.js:27 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'onSnapshot') Here is the code sni ...

Using Node.js, Express.js, and Redis.io for efficient order processing

Currently, I am working on a project that involves Node.js with express.js and redis.io as the database. I have implemented a get resource with query parameters to retrieve the IDs of libraries containing a specific book. However, I am struggling to unders ...

Exploring Angular: Techniques for searching within nested arrays

I am looking for a function that can search and filter the largest value in a nested array, and then return the parent scope. Here is an example of my array: data = {"people": [{"male": [ {"name": "Bob" ,"age": "32"}, {"name":"Mike", "age ...

Upon attempting to fetch input by name, Puppeteer reported the error message: 'Node is not clickable or not an HTMLElement'

This is the structure of my HTML: <div id="divImporte"> <p class="btn01"> <input type="button" name="Enviar Tasas" value="Enviar Tasas"> </p> </div> Here are the diffe ...

transferring information from child to parent with the help of Vue.js and Laravel

As a newcomer to vue.js, I have a child component called 'test' and a parent component called 'showdata'. My issue arises when I try to emit data from the child to the parent - while the emission is successful, displaying the data in th ...

What steps should I follow to bring in an animated SVG file into Next.js 13 without losing transparency and animation effects?

How to Include an Animated SVG File in Next.js 13 import Image from "next/image"; export default function Home() { return ( <main className="flex h-screen flex-col items-center"> <div className="container mt-1 ...

Warning: Unhandled promise rejection detected

I'm encountering an issue with Promise.reject A warning message pops up: Unhandled promise rejection warning - version 1.1 is not released How should I go about resolving this warning? Your assistance is greatly appreciated public async retrieveVe ...

problem with the video pathway in the javascript document

I'm currently in the process of putting together a Video gallery playlist using HTML, CSS, and JavaScript. So far, I've set up the html and css files along with two js files. The first js file contains all the video information as shown here: ...

Leveraging the power of Firebase and JavaScript to easily include custom user fields during the user

UPDATE: I encountered an issue while using Nextjs framework. However, it works perfectly fine when I use a vanilla CRA (Create React App). It appears that the problem is somehow related to Nextjs. I'm currently working on creating a new user document ...

Encountering a theme issue in the makeStyles function within Material-UI version 5

While working on some React components, I created a styles.js file for each of them. I am following a YouTube tutorial that uses material-ui version 4, so I decided to upgrade to V5. Code snippet for the component (Form): import React from 'react&apo ...

"Create a smooth transition effect in CSS by fading out one div and fading in

I've set up a grid of buttons, and my goal is to have the grid fade out when a button is clicked, then fade in with a new div in its place. This involves animating opacity from 1 to 0 and vice versa while toggling the display:none property for content ...

What is the best way to clear an XML or table?

As I delve into learning Javascript, I've been experimenting with different approaches to achieve a specific functionality. I'm trying to implement a button that can toggle or hide XML data in a table. My attempts so far have involved adding anot ...

Fixing the problem of digest overflow in AngularJS

I've been working on a code to display a random number in my view, but I keep encountering the following error message: Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting! It seems to be related to a digest outflow issue, and I&apo ...

Running JavaScript in selenium and obtaining the result

I'm currently utilizing JavaScript with Selenium WebDriver. Here is a snippet of my code: let return_value = driver.execute_script(script) However, I am unsure how to retrieve the value from my script. const token = await grecaptcha.enterprise.exec ...