How to write reusable date in date-fns?

49 Views Asked by At

I wrote below code to display date in my small Weather App. Date display correctly but in back of my head I have an idea that I need to try write reusable code. How I can combine "const date and day" and use it separately?

import { Weather } from "./type";
import { format } from "date-fns";
import { pl } from "date-fns/locale";

interface Props {
  weather: Weather;
}

export default function WeatherApp({ weather }: Props): JSX.Element {
  const date = format(new Date(weather.dt * 1000), "LLLL dd, yyyy", {
    locale: pl,
  });

  const day = format(new Date(weather.dt * 1000), "eeee", {
    locale: pl,
  });

  return (
    <div className="container-weather">
      <div className="container-header">
        <h2 className="header">{weather.name}</h2>
      </div>
      <div className="container-data-forecast">
        <p className="data-forecast">
          Day: {day.charAt(0).toUpperCase() + day.slice(1)}
        </p>
        <p className="data-forecast">
          {date.charAt(0).toUpperCase() + date.slice(1)}
        </p>
      </div>
      <div className="container-data-forecast">
        <p className="data-forecast">
          Temprature: {weather.main.temp.toFixed(2)}°C
        </p>
        <p className="data-forecast">Humidity: {weather.main.humidity}%</p>
      </div>
    </div>
  );
}

I have no idea how I can do that because I'm still learning.

1

There are 1 best solutions below

0
Mr. Polywhirl On BEST ANSWER

Just create a function i.e. formattedDate that returns an object i.e. FormattedDateRecord:

const DATE_FORMAT = "LLLL dd, yyyy";
const DAY_FORMAT = "eeee";

interface FormattedDateRecord {
  date: string;
  day: string;
}

function formattedDate(weather: Weather): FormattedDateRecord {
  const localeOptions = { locale: pl }; // Could also be constant?
  const date = new Date(weather.dt * 1e3);
  return {
    date: format(date, DATE_FORMAT, localeOptions),
    day: format(date, DAY_FORMAT, localeOptions),
  };
}

// ...

const { date, day } = formattedDate(weather);