UI developer tutorials and guides

Friday, June 24, 2022

Create a simple store in Solidjs

 Stores are way to distribute collected data among components. In Vuejs Vuex (default) and Pinia stands for stores and for React, you have to choose one like Redux.

Solidjs provides inbuilt store. There are two way to create a store, create a store using createStore method or create a mutable store using createMutable.

A mutable store allow us to directly access and modify data, no need for getters and setters. We goes this way. ➡ 

Create Store

Create a store and export it, so that rest of the modules can access it.

export const store = createMutable({ myText: "" });

 Accessing in component

The component can be accessed and modified using as regular JavaScript objects.

import store from './store'

console.log(store.myText)

Read more about Mutable store


Read More

How to apply refetch logic in Solidjs

 In Reactjs libraries such ReactQuery make API fetching so simple and fast. Solidjs also come with powerful tools. 

We have already seen how to fetch API using the Resource feature. πŸ‘“ 

Sometimes we need to fetch the API again under special circumstances such while network failure,  require to fetch content in a regular intervals etc.

Resource provide us way to re-fetch/ reuse the function. It really do return a re-fetch function and DOM will automatically render the changes after the re-fetch, since it a reactive signal.


const [posts, {refetch}] = createResource(() =>
....
);

How to call the re-fetch and where to call ? πŸ˜‰

One of the ideal use is combine the call with a createEffetct.

In our example we have a search component and want to re fetch particular content based on the search text as the user type in.

createEffect((prev) => {

if (prev !== searchStore.searchString) {
console.log("Search Text changed");
refetch()
}
});

 That's all you need to know about refetch

 

 

Read More

How to set focus to a input in Solidjs

When we required to access the element in the DOM we can use the Ref. It is similar to the Ref in React.

Suppose we have a input text box deeper in the return statement and want to set focus when it rendered, then Ref become handy πŸ–.

Here is the quick example

function Component(){ let myBox;
setTimeout(() => myBox.focus());
return(<> <div> <input ref={myBox} type="text"/></div> </>)}

Here in the Solidjs component example we done the following

  • created a variable myBox
  • Set ref to input box - ref={myBox}
  • Accessing the ref element and set focus to the input.
     


Read More

Wednesday, June 22, 2022

Quickly remove duplicates from array in Javascript

 Suppose we have array with duplicate values. How do we remove then duplicates? I remember Python have simplest way for that and JavaScript have such capabilities too.

let langs=["Vuejs","Angular",Vuejs",Reactjs","Solidjs","Reactjs"];

Here we have duplication values. To remove them, we can looping through each item. There is another way.

Set

Unlike array Sets only store unique values. So lets convert our array to Set with constructor.

const myset= new Set(langs)

 Remember set object will look like the following

{"Angular",Vuejs",Reactjs","Solidjs"}

Back to array

We have to put the values back to array using the spread operator.

langs=[...myset]

Read more JavaScript tips @ JSSU

 

Read More

Tuesday, June 21, 2022

How to setup 404 route in solid-app-router

 404 or commonly known as page not found is must have for any web app. How do we setup the🎭 route and manage the error page ?

Build a beautiful πŸ‘§ error component with 😎 animation.

This example uses solid-app-router , let's setup a router with wild card in App.jsx

<Route path="*" element={() => <PageNotFound />} />

Here the path can be anything which doesn't exists, such as /download , /faq etc and the PageNotFound is just another page component.

When you hit http://localhost:3000/faq the PageNotFound will render if the route is not defined.

Read More

Create a fallback component in Solidjs

 Solidjs offer interesting features that let you conditionally render component. Vuejs and Reactjs didn't offer such a component as I know.

It will be very help full, 😊 When fetching API data and sometimes the data may not retrieve correctly and you can use the <For> component's fallback with an arrow function to render a loading component instead.

Solidjs also provides Show component which help us conditionally render components. The Show component is more applicable in the above mentioned case.

<Show
when={posts()?.length>0}
fallback={() => ( <GridSkelton /> )}>
<For each={posts()}>{(post) => <PostCard post={post} />}</For>
</Show>

Here the Show will check  posts Resource signalπŸ“Ά and make sure the data received properly and then proceed to render it. 

We can also use the fallback in a For component too. 

Read More JavaScript Guides on JavaScript Super User

 

Read More

Saturday, June 18, 2022

Fetch data from graphql API in Solidjs

 I am super excited about the Solidjs, the πŸš€ speed JavaScript framework. In this I will show you how to read data from a

Graphql endpoint. 

There are libraries such as Apollo which used a React specific approach, so I decide to use another library called URQL  

 

How to ?

For reading async data Solidjs provides us Resources, which is a signal. We can combine URQL client within the createResource command with an arrow function.

Install the dependencies

We need two  dependencies for using graphql namely, graphgql and @urql/core

yarn add graphql @urql/core

 

URQL Client

In this example I used a mock graphql API,also  stored the URL in .env (which require vite configuration) file. Let's initialize out API with url

import { createClient } from "@urql/core";
const client = createClient({
url: API_GQL,
});

Create Resource and fetch 

We can either create another function for fetching data as in REST API fetcher or simplify go with an arrow function as follow.

const [posts]= createResource(()=>client.query(`
query {
posts {
title
id
excerpt
featured_image
}
}
`).toPromise().then(data=>{
return data.data.posts
}));

 

 Rendering the data

We can use Show and For components to render the list. Show let's allow check the data is available for render, it may contain null or undefined.

<Show when={posts()}>
<For each={posts()}>{(post) => <PostCard post={post} />}</For>
</Show>

 Read More GQL posts

 

 

 

Read More

Tuesday, June 14, 2022

How to use tailwindcss in Solidjs

 CSS is the most important part of UI development. There are lots of frameworks and libraries such as bootstrap, bulma to make thing easier. Each on has its own use cases.

I prefer using TailwindCSS, it help me to build responsive layout and utility approach save a lot of time and code. 

How do we use tailwindCSS in Solidjs ? We have two options one is use the Tailwind with handy πŸ– features, WindiCSS or go with Latest Tailwind features.

Tailwind   

Configuring Tailwind on Solidjs is similar to Reactjs. We have to go through

  • Install dependencies
  • Generate config and configure content section
  • Integrate classes and components

A detailed guide is here , in case you need them.

WindiCSS

WidniCSS comes with vite configuration, it is make thing easier for Solidjs users. Here is the guide required.

Read More

Dynamic routes and params in Solidjs

 This example based on solid-app-router library. Dynamic routes are those route which are similar to /user/1 /post/79 /tag/tag-name

Note the value 1 and 79 these are used to access particular data from backed. In our case the post with id 79 or user with id 1. These value called parameters.

So how do we setup a dynamic route in Solidjs ?

<Route path='/posts/:id' element={<div>this is a dynamic route </div>}/>

Here we used :id to pass a parameter to the route. In Nuxtjs / Nextjs we used [id].js to deal with dynamic route, in Solidjs we can achieve this in Router definition.

How to access the params ? 

We have to read params from the Route component, it can be arrow function as follows.

import { useParams } from "solid-app-router";
()=>{
const route= useParams()
;}

 Then we can pass the value to the component, the complete Route definition will look like as follows.

<Routes>
<Route path='/' element={Home}/>
<Route path='/posts/:id' element={()=>{
const route= useParams();
return(<SinglePost id={route.id}/>)}}/>
</Routes>

 

Read More

Ceate a mock API using Github and Mockend

It's wise to establish a backed setup first, so that UI developers can test the data. So UI team has to wait for the later to complete job. 

The activation for single repo work only once, switching between repo will not work, it may cause to expire the mockend plan.

Mocking data is a great in such situations is a must. How to create mock API with custom data? 

So how do we create our own mock data with out a server?

We can create a REST and Graphql API using mockend.com and Github repository. For free usage only one repository can be activated.



In the Repository we have to setup the mock JSON file. (.mockend.json)

"User": {
"title": { "string": {} }
}
}

The title will be automatically generated for us. For advance use case we can use custom values and lorem strings.

Then the API can be read using any API client such as POSTMAN or Insomnia. The Graphql is worked for me using the Apollo Studio 

REST API URL:  mockend.com/org/repo/post

Replace the org with organization / user-name and repo with repository name.

The Graphql API URL will be  

mockend.com/org/repo/graphql

 

 

 


Read More

How to use environment variables in Solidjs [vitejs]

 Environment variables can be used in JavaScript application (Nodejs) to store information such API SECRETS. 

Reactjs has inbuilt capacity to consume .env files while Solidjs have to go through vite config..

First up all create .env file at the project root with some information .

API_URI = SOME SECRET

 Configure in vite.config.js

Add a define key ⚿ to the configuration settings as follows in vite.config.js file πŸ“‚.

import { defineConfig, loadEnv } from 'vite'

export default defineConfig(({ command, mode }) => {
const env = loadEnv(mode, process.cwd(), '')
return {
// vite config
define: {
API:JSON.stringify('https://jsonplaceholder.typicode.com/posts'),
APP_ENV: JSON.stringify(env.API_URI)
},
plugins: [solidPlugin()],
build: {
target: 'esnext',
polyfillDynamicImport: false,
},
}
})

Read Official Doc on vite more information β„Ή

 



Read More

How to create global variable in vitejs [Solidjs]

 Vitejs is build tool for modern nodejs applications. Global variable requires in any application where common information need to be accessed in different modules. 

It is common practice is that store values such as URL, KEYS in separate files, in such cases we can use either environment variable or project level symbols.

Read More

Setup windicss for Solidjs

Windicss is the next generation utility CSS framework, for me it is like a simplified tailwind with some jet pack features, it is awesome πŸ˜‚ 


 

Let's configure Windicss for Solidjs project. We are going through following steps.

  • Initialize/create Solidjs a project
  • Install dependencies
  • add vite pluginπŸ”Œ
  • Configure vite config
  • Add windicss to entry point file.

First up all create a new project add all dependecies for Solidjs and windicss.

npx degit solidjs/templates/js my-app yarn install

Let's install vite plugin πŸ”Œ I

Read More