Checking for undefined in Solidjs

How to deal with undefined in Solidjs


First time I am very unsure about how to dealing with undefined object in Solidjs. Hopefully there is a better way to do this.

You may meet the undefined object when accessing a set of objects, like posts and pass to other components.

Undefined can be tackled using ?. as follows.

  <Post post={post()?.post_type}/>   

Here solid will check the post_type object which can be undefined for some point of time.

Similarly, we can also implement the login in template

   { props.post?.title[0].text  || "Post title"}

Contentful service in Angular

Create contentful service and integrate contents with Angular.


In Angular, service is a module where data fetching and implement CMS integration and later inject the service in components and modules.

Contentful

Contentful is headless CMS, a service like Word Press, can used to create backend for content oriented web/mobile app.

For integrating contentful CMS with Angular, first we need a service to inject data to components, also require the contentful package

Create a new Angular project, and add the dependency

ng new myproject 
yarn add contenful

let’s add a service

ng g s contentfulservice 

this will add a service to your project

add a client and fetchPost method in the service

import { createClient,Entry } from 'contentful';
import { Injectable } from '@angular/core';
import {from, Observable} from 'rxjs';
import { environment } from '../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class BlogAPIService {
  private  clinet = createClient(environment.config);
  constructor( ) {   }

  fetchPosts() {
    const promise=this.clinet.getEntries();
  return  from(promise);
  }

 

} 

In the above we converted the promise to observable using from .

Also need to configure the environment file configure the contentful credentials which can be obtained from contentful setting (API)

 
export const environment = {
  production: false,
  config: {
    space:'w591jyzdi2py',
    accessToken:'DXG7DohnxRncpcxSPtLGr5fR4_fzjyzRzVZAiP9Ussk'
  }
};
 

Inject the service

In any component , inject the service using the constructor as follows

Here is home component example.

import {Component, OnInit} from '@angular/core';

import {BlogAPIService} from '../blog-api.service';
import {Observable} from "rxjs";

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  entries$:Observable<any> | undefined;

  constructor(private blogService:ContenfulService) {
  }


  ngOnInit(): void {
     this.entries$=this.blogService.fetchPosts();
  }

} 

In the template we can convert the observable and render using *ngif

 <main *ngIf="entries$ | async as entries"> 
{{entries | json}}
</main>

Svelte : enabling markdown content using preprocess

How to use markdown content in Svelte


We can use any markdown content with Svelte and render them using library you prefer. But there is a better way. 🥊the preprocessors.

Anyway markdown is the easiest way generate html document, usually found on the Github documentation (readme.md). Wanna learn more ? Here is the right place where you can start. Spend few minutes to learn.

MDSVEX

So which preprocessor should I prefer. ? MDSVEX

It allow us to use the svelte components inside markdown and markdown inside components too. It is interesting, isn’t it ? 😆

Add the MDSVEX and auto configure using the CLI.

npx svelte-add mdsvex

It will configure the add msdsvex.config and will be imported on svelte.config file.

//mdsvex.config
import { defineMDSveXConfig as defineConfig } from 'mdsvex';

const config = defineConfig({
	extensions: ['.svelte.md', '.md', '.svx'],

	smartypants: {
		dashes: 'oldschool'
	},

	remarkPlugins: [],
	rehypePlugins: []
});

export default config;
//svelte.config
import { mdsvex } from 'mdsvex';
import mdsvexConfig from './mdsvex.config.js';
import adapter from '@sveltejs/adapter-auto';
import preprocess from 'svelte-preprocess';


const config = {
	extensions: ['.svelte', ...mdsvexConfig.extensions],

	kit: {
		adapter: adapter()
	},

	preprocess: [mdsvex(mdsvexConfig)]
};

export default config;

Use markdown in Svelte component ?

Before using markdown in a component , we have to config the MDSVEX extensions list.

Include .svelte in the array of extensions in the mdsvex.config

import { defineMDSveXConfig as defineConfig } from 'mdsvex';

const config = defineConfig({
	extensions: ['.svelte.md','.svelte', '.md', '.svx'],

..... other boring stuff 💤 
});

export default config;
 

Now we can even create an about page using mark down 👇 and can use on any component too.

  //route/about.md  or about.svx

# About

It is all about where ***my life begins.....***

and it will work. 🚀

Svelte : rendering markdown

How to render markdown content in Svelte


We can use any markdown content with Svelte and render them using library you prefer. My choice is using svelte-markdown.

Svelte also supports preprocessor, which enable us to use markdown instead of html. We will discuss the topic in preprocess .

It is optimized for Svelte and easy to use. Let’s add the dependency and configure

 npm i svelte-markdown

Here is simple example.

<script>
  import SvelteMarkdown from 'svelte-markdown'
  const source = `
  # This is a header

This is a paragraph.

* This is a list
* With two items
  1. And a sublist
  2. That is ordered
    * With another
    * Sublist inside

| And this is | A table |
|-------------|---------|
| With two    | columns |`
</script>

<SvelteMarkdown {source} /> 

That’s all I got.

Svelte : Async fetch in Routes

Svelte : How to fetch data in dynamic route or at any route


How do we fetch data from API in a dynamic route in Svelte ?

Similarly fetch data in a store, can do the same using a module level load script which run before the rendering occurs.

In the component (dynamic route, say /pokeman/[id].svelte) define a load function with context as module.

<script context="module" >
export async function load({ params, fetch, session, stuff }) {
    const {id} = params;
        
    const url=`https:\\pokeapi.co/api/v2/pokemon/${params.id}`;
    const res= await fetch(url);
    return {
      props: {
        pokeman: res.ok && (await res.json())
      }    
  }
 
  return {
    status: 404
  };

}
</script>
 

In the above we fetch data from a pokeman API. Load function accepts params, and fetch as argument and will run top of the component once.

The data fetched will returned as props and and can access in regular script tag.

<script>
<script>
export let pokeman;
</script> 

In the above code we exported the pokeman object, hence available in the html block.

How to access params in Svelte route

Svelte : Accessing params in a dynamic route


Accessing params in Svelte route can be possible with get function and load function.

Component level load function

A component level load function is special function (module) which will execute once and before the component rendered.

<script context="module">
	// @ts-ignore
	export async function load({ params }) {
		return {
			props: {
				section: params.section
			}
		};
	}
</script> 

The prop section can be accessed and exported from the regular script as follows

<script>
export let section;
</script> 

Alternatively we can use the get function to access the params. See the Documentation

Store in Svelte

How to create a writable store in Svelte


Svelte come with a store module for distribute data among components and routes.

Create writable store

We can create writable store using the Writable from svelte/store . Following is an example created with Svelte-Kit in which a fetch operation performed and data stored to our store docs.

//store.docstore.js

import { writable } from "svelte/store";
export const docs=writable([]);

const fetchDocs=async()=>{
    try{
    const url=`https://my-json-server.typicode.com/devmnj/mockdb/docs`;
    // const url=`https://mockend.com/manoj-ap/mockbackend/docs`;

    const res= await fetch(url);
    const data= await res.json();
    docs.set(data);
    }
    catch{
        console.log('Got error in fetching');
    }
};
fetchDocs();  

Using the store

We can import the store in any component and can access the value of store by prefixing $ sign.

<script>
import { docs } from '../store/docsstore';
log.console($docs)
</script>

That’s all I got.

Lit web components

About Litjs custom web component and Frameworks


Lit is a Javascript library from the house of Google. It is a tiny library and can be a powerful tool for develop reusable web components and apps.

We can create native web component/custom html Tags using Lit with reactivity and other feature mostly offered by libraries like Reactjs.

Also note that it is possible to create custom HTML tags not using any of these libraries, but with a simple Vanilla script.

These libraries simplify our tasks.

Lit web components is compatible with React, Vue or even with HTML pages.

React example

Here is a React Lit example.

Lit Animation

I love making Lit component, do you? 😆

Create a svelte app from scratch


I am excited about svelte, are you?. You can use the vite command to build a app indeed. It will create structure and dependencies for a regular app ?

npm init vite my-app -- --template svelte 

Svelte Kit

Wanna complete setup for a project with full configuration and route setup. Try the new Svelte Kit.

npm create svelte my-app
cd my-app
npm install
npm run dev -- --open  

Svelte Kit uses Vite build tool.

Explore the directory structure. You made it. 😂

How to pass data to component from the router setup – solid-app-router

How to pass data from the router setup to the component in solid-app-router


The data prop of the Route component allow us to pass the data to router component. The solid-app-router (Solidjs) also require that a data function should be passed to data prop.

The function

The data function can access params internally. We need not pass it directly.

function getData({ params, location, navigate, data }) {
       
     
  
  return params.id;
} 

Router setup

In the router setup we pass the data as follows

  <Route path="/" element={Home} data={getData} />

The Home component

In the Home component we have use the useRouteData hook to receive the data.

import { useRouteData } from "solid-app-router";

export default function Home(props) {
  const data = useRouteData();
  return (
    <>
      <div>
      { data }
      </div>
    </>
  );