Reputation: 441
I'm trying to convert the data am getting from the dateRange
variable, but I'm getting an error: Argument of type 'Date | undefined' is not assignable to the parameter of type 'number | Date'. Type 'undefined' is not assignable to type 'number | Date'
.
What's wrong with my code?
//header file
import { useContextState } from '../context/context'
const Header = () => { const { dateRange, setDateRange, setOpenDate, openDate } = useContextState()
return (
<span onClick={() => setOpenDate(true)} className="cursor-pointer">
{`${format(dateRange[0].startDate, "MM/dd/yyyy")} To ${format(dateRange[0].endDate, "MM/dd/yyyy")}`}
</span>
</nav>
)
}
export default Header
// context.tsx file
import { createContext, Dispatch, SetStateAction, useContext, useState } from "react";
import { addDays } from 'date-fns';
import { Range } from "react-date-range";
import { format } from "date-fns";
export interface Range {
startDate?: Date | undefined ;
endDate?: Date | undefined;
key?: string | undefined
}
interface IstateContext {
openDate: boolean
setOpenDate: Dispatch<SetStateAction<boolean>>
dateRange: Range[]
setDateRange: Dispatch<SetStateAction<Range[]>>
}
const initialState = {
openDate: false,
setOpenDate: () => false,
dateRange: [{
startDate: new Date(),
endDate: new Date(),
key: "selection",
}],
setDateRange: () => void{}
}
const StateContext = createContext<IstateContext>(initialState)
interface Childern {
children: React.ReactNode
}
export const ContextProvider: React.FC<Childern> = ({ children }) => {
const [openDate, setOpenDate] = useState<boolean>(false)
const [dateRange, setDateRange] = useState<Range[]>([
{
startDate: new Date(),
endDate: new Date(),
key: "selection",
},
])
return (
<StateContext.Provider value={{ dateRange, setDateRange, openDate, setOpenDate
}}>
{children}
</StateContext.Provider>
)
}
export const useContextState = () => useContext(StateContext)
Upvotes: 1
Views: 510
Reputation: 92
Check 'Range'. You have imported from "react-date-range". And also you have made an interface that is unable to overite the property.
replace the third line with the code and confirm if it works. "added null check"
{${format(dateRange[0]?.startDate, "MM/dd/yyyy")} To ${format(dateRange[0]?.endDate, "MM/dd/yyyy")}
}
Upvotes: 0
Reputation: 2486
If I understand the question correctly you want to pass dateRange.0.startDate/endDate
to the format
function however the values could be undefined and format
does not accept undefined values.
Using type guards you can check against undefined values and handle that case.
const range = dateRange?.[0];
if (range?.startDate === undefined || range?.endDate === undefined) {
return <span>Invalid range!</span>
}
return (
<span onClick={() => setOpenDate(true)} className="cursor-pointer">
{`${format(range.startDate, "MM/dd/yyyy")} To ${format(range.endDate, "MM/dd/yyyy")}`}
</span>
)
Upvotes: 0