I have been working on an SPA with React 18 and The Movie Database (TMDB) API.
I need to format dates nicelly in this app. For this purpose I use Moment.js.
In src\utils\datetime-formatter.ts I have:
import moment from "moment";
function dataTimeFormatter() {
const formatDateLong = (value) => {
return moment(value).format("MMMM DD, YYYY");
};
const formatDateShort = (value) => {
return moment(value).format("MMM DD, YYYY");
};
const yearsAgo = (value) => {
return moment(value, "YYYYMMDD").fromNow(true);
}
}
export default dataTimeFormatter;
In the component I need to use it I have:
import dataTimeFormatter from "../../utils/datetime-formatter";
function Actordetails() {
// More code
return (
<div className="row">
{actor.birthday && actor.place_of_birth ?
<p className="birth-info small">
Born in <strong>{actor.place_of_birth}</strong>, on <strong>{formatDateLong(actor.birthday)}</strong>
</p> : <></>
}
</div>
);
}
The problem
The tewrminal shows this error (from Actordetails.jsx):
‘formatDateLong’ is not defined
From datetime-formatter.js, the erro is:
‘formatDateLong’ is assigned a value but never used
Questions
- What is my mistake?
- What is the most reliable way to fix the bug?
>Solution :
The three utility functions you’ve created only exist as local variables inside dataTimeFormatter. If someone were to call dataTimeFormatter, it would start running, create 3 local variables, and then finish running, at which point those 3 variables can be garbage collected.
You need to rewrite it so the functions are not local variables. There’s a couple ways you could do this. For example, you could export the individual functions:
export const formatDateLong = (value) => {
return moment(value).format("MMMM DD, YYYY");
};
export const formatDateShort = (value) => {
return moment(value).format("MMM DD, YYYY");
};
export const yearsAgo = (value) => {
return moment(value, "YYYYMMDD").fromNow(true);
};
// Used like:
import { formatDateLong } from "../../utils/datetime-formatter";
//...
<strong>{formatDateLong(actor.birthday)}</strong>
Or you could put the functions on an object and export that:
const dateTimeFormatter = {
formatDateLong: (value) => {
return moment(value).format("MMMM DD, YYYY");
},
formatDateShort: (value) => {
return moment(value).format("MMM DD, YYYY");
},
yearsAgo: (value) => {
return moment(value, "YYYYMMDD").fromNow(true);
},
};
export default dateTimeFormatter
// used like
import dateTimeFormatter from "../../utils/datetime-formatter";
// ...
<strong>{dateTimeFormatter.formatDateLong(actor.birthday)}</strong>