Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 2, 2022 10:40 am GMT

An Opiniated React Stack

Simplicity & Aesthetics over Complexity
Life is too sweet to be loosing sleep over trying to understand how a library or framework works, as long as a solution or library is working and has long term support I'm okay with it

Recoil JS

Example with async queries

using useRecoilValueLoadable hook.

This hook is intended to be used for reading the value of asynchronous selectors. This hook will implicitly subscribe the component to the given state.

This hooks returns a Loadable object for the current state with the following interface:

  • state: Indicates the status of the selector. Possible values are 'hasValue', 'hasError', 'loading'.
  • contents: The value represented by this Loadable. If the state is 'hasValue', it is the actual value, if the state is 'hasError' it is the Error object that was thrown, and if the state is 'loading', then it is a Promise of the value.

The example code below implements useRecoilValueLoadable hook from recoilJS using Next JS, in a use-case when implementing private routes using HOC

import { useRouter } from "next/router";import React from "react";import { useRecoilValueLoadable } from "recoil";import getAuthUser from "../store/selectors/getAuthUser";const withAuthConsumer = (WrappedComponent: any) => {  return (props: any) => {    const authUser = useRecoilValueLoadable(getAuthUser);    const router = useRouter();    // checks whether we are on client / browser or server.    if (typeof window !== "undefined") {      if (authUser.state == "loading") {        return null;      }      if (        authUser.state == "hasValue" &&        authUser.contents?.user_type == "consumer"      ) {        return <WrappedComponent {...props} />;      } else if (        authUser.state == "hasValue" &&        authUser.contents?.user_type == null      ) {        router.push("/auth/login");        return null;      } else {        router.push("/auth/login");        return null;      }    }    // If we are on server, return null    return null;  };};export default withAuthConsumer;

Check this useRecoilValueLoadable for more explanation.

Html to jsx

https://htmltojsx.in/


Original Link: https://dev.to/kachidk/an-opiniated-react-stack-im6

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To