Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Last active June 2, 2023 17:07
Embed
What would you like to do?
import type { V2_HtmlMetaDescriptor, V2_MetaFunction } from "@remix-run/node";
export const mergeMeta = (
overrideFn: V2_MetaFunction,
appendFn?: V2_MetaFunction,
): V2_MetaFunction => {
return arg => {
// get meta from parent routes
let mergedMeta = arg.matches.reduce((acc, match) => {
return acc.concat(match.meta || []);
}, [] as V2_HtmlMetaDescriptor[]);
// replace any parent meta with the same name or property with the override
let overrides = overrideFn(arg);
for (let override of overrides) {
let index = mergedMeta.findIndex(
meta =>
("name" in meta &&
"name" in override &&
meta.name === override.name) ||
("property" in meta &&
"property" in override &&
meta.property === override.property) ||
("title" in meta && "title" in override),
);
if (index !== -1) {
mergedMeta.splice(index, 1, override);
}
}
// append any additional meta
if (appendFn) {
mergedMeta = mergedMeta.concat(appendFn(arg));
}
return mergedMeta;
};
};
import { mergeMeta } from "./merge-meta";
export const meta = mergeMeta(
// these will override the parent meta
({ data }) => {
return [{ title: data.project.name }];
},
// these will be appended to the parent meta
({ matches }) => {
return [{ name: "author", content: "Ryan Florence" }];
},
);
// both functions get the same arguments as a normal meta function
@AltanS
Copy link

AltanS commented Mar 8, 2023

How would I go about using this similar to the loader data to have the types available?

I've tried this:

  const data = useLoaderData<typeof loader>();

This works in my IDE, but throws an error on the server: You cannot useLoaderData in an errorElement (routeId: root)

@sinitsa
Copy link

sinitsa commented May 20, 2023

How would I go about using this similar to the loader data to have the types available?

This works in my IDE, but throws an error on the server: You cannot useLoaderData in an errorElement (routeId: root)

	({ data }: V2_ServerRuntimeMetaArgs<typeof loader>) => {

@sergiocarneiro
Copy link

This is an important feature, at least for me. Is this likely to be included in the core library? If not, I may publish an improved version in remix-utils.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment