feat: query only JSON scripts

This commit is contained in:
Ayo Ayco 2023-07-18 22:23:21 +02:00
parent 1d7def5ea7
commit ef8c086972
2 changed files with 10 additions and 2 deletions

View file

@ -96,7 +96,9 @@ export interface Props {
### Using a custom serializer and parser
You can bring your own serializer/parser. For serializing data that `JSON.parse` cannot parse (e.g., Date or BigInt), here's an example of using Rich Harris' `devalue`
If you want to opt for more complex data, you can bring your custom serializer/parser.
Here's an example of serializing data that `JSON.stringify` cannot (e.g., Date or BigInt) using Rich Harris' [`devalue`](https://github.com/Rich-Harris/devalue):
```astro
---
@ -125,6 +127,12 @@ export type Data = typeof data;
</script>
```
### Errors & Warning in `deserialize()`
The `deserialize()` function may give you the following:
1. **ERR: No match found** - there are no `JSON` scripts with the given ID
1. **WARNING: Multiple matches for <id>** - there were multiple `JSON` scripts found with the same ID
## About
This is a quick and easy pattern to embed serialized information into your HTML and make it available in the client-side script with type safety.

View file

@ -28,7 +28,7 @@
* ```
**/
export function deserialize<T = any>(id: string, parser?: (serialized: string)=>any): T {
const elements = document.querySelectorAll<HTMLScriptElement>(`#${id}`);
const elements = document.querySelectorAll<HTMLScriptElement>(`script#${id}[type="application/json"]`);
if (elements?.length > 0) {
if (elements?.length > 1)