How do I use a fetched variable as initial state for material UI datepicker?

Viewed 102

I am fairly new to Reactjs and I am trying to build a woocommerce account profile for a subscriptions site. Therefore, I want to display the async fetched subscription's next payment date as the initial value of the material UI Daypicker. However, I can't find a way to do this.

I tried to use a hook with its initial value on the next payment date, however, the state initial value can't be async. If I choose to set the state with the next payment date, the date picker is first set to the current date. Moreover, If I try to update it using UseEffect, it is put back to the initial state every time I try to update the date picker to a new date.

What am I missing to set the initial value of the hook to be the next payment date of the subscription with the possibility to update to a new date?

Thank you a lot.

import React, { useEffect, useState } from 'react';
import { getSubscription } from '../queries/subscriptions';
import Select from 'react-select'
import AdapterDateFns from '@material-ui/lab/AdapterDateFns';
import LocalizationProvider from '@material-ui/lab/LocalizationProvider';
import DatePicker from '@material-ui/lab/DatePicker';
import TextField from '@material-ui/core/TextField';


const GetSubscription = () => {
    const userId = localStorage.getItem('user_id')
    const [subscriptions, setSubscriptions] = useState([]);
    const [nextDate, setNextDate] = useState();
    useEffect(() => {
        if (userId) {
            getSubscription(userId, setSubscriptions)
        }

    }, [userId]);
    
    const handleClick = (e) => {
        setSubscriptions({ ...subscriptions, id: e.value, label: e.status })
    }
    
    if (subscriptions.selectOptions) {
        return (
            <div>
                <Select options={subscriptions.selectOptions}
                    onChange={handleClick}
                    defaultValue={subscriptions.selectOptions[0]}
                />


                <LocalizationProvider dateAdapter={AdapterDateFns}>
                    
                    <DatePicker
                        disablePast
                        variant="static"
                        label="Responsive"
                        openTo="date"
                        views={['date']}
                        value={nextDate}
                        onChange={(date) => {setNextDate(date);}}
                        }
                />

                 </LocalizationProvider>
            </div>
        )
    } else {
        return <>Aan het laden....</>;
  }
    
}

export default GetSubscription

Get subscription Function:


export const getSubscription = async (userId, setSubscriptions) => {
        const result = await fetchSubscription(userId)
                
        const data = result?.data || []

        const options = data.map(d => ({
            "value": d.id,
            "label": "#" + d.id + " - " + d.billing.first_name + " " + d.billing.last_name,
            "billing_interval": d.billing_interval,
            "start_date": d.start_date,
            "next_payment_date": d.next_payment_date,
            "products": d.line_items,
            "billing": d.billing,
            "shipping": d.shipping,
            "price": d.total
        }))

    setSubscriptions({
            data: data,
            selectOptions: options,
            id: data[0].id,
            billing_interval: data[0].billing_interval,
            start_date: data[0].start_date,
            next_payment_date: data[0].next_payment_date,
            products: data[0].line_items,
            billing: data[0].billing,
            shipping: data[0].shipping,
            price: data[0].total
        })
    
    }


const fetchSubscription = async (userId) => {
            return axios
                .get('http://www.localhost//wp-json/wc/v1/subscriptions?customer=' + userId, {
                    headers: {
                        'Content-Type': 'application/json',
                        Authorization: `Bearer ${localStorage.getItem('token')}`
                    }
                })
                .catch((err) => console.log(err));
}

1 Answers

You can set the value initially in the state

const [nextDate, setNextDate] = useState(new Date());
Related