gauravbytes.com is now codefoundry.dev.
Showing posts with label React Redux. Show all posts

In the previous post, we created a BlogPost application with React and Redux and managed global state with Redux. We will extend the same application and will introduce Next.js for server-side rendering. The bigger benefit of using Next.js is pre-rendering of the page along with automatic code-splitting, static site export, CSS-in-JS.

Next.js functions

Next.js exposes three functions for data fetching and these are getStaticProps, getStaticPaths and getServerSideProps. First two functions are used for Static generation and the last function getServerSideProps is used for Server-side rendering. Static generation means the HTML is generated at the build(project build) time whereas in Server-side rendering HTML is generated at each request.

Adding required libraries

Run npm i --save next @types/next from root of the project to add the required libraries for this example.

Update following commands under scripts in package.json.

"dev": "next dev",
"start": "next start",
"build": "next build"

Next.js is built around the concept of pages. A page is nothing but a React component exported in pages directory. For example; pages/welcome.tsx will be mapped to /welcome. You also have an option to have Dynamic routes.

Basic setup

Let's start with creating _document.tsx and _app.tsx under src/pages directory. In _document.tsx, you defines your skeleton structure of your html page generated by Next.js. You usually do this to add meta tags or loading scripts or styles from CDN. Consider _app.tsx as the root component of your React application. In our example, we provide redux store to the Provider in this component.

// _document.tsx


import React from 'react';
import Document, { Html, Head, Main, NextScript } from 'next/document'

export default class MyDocument extends Document {
  render() {
    return (
    <Html lang="en">
      <Head>
        <meta content='https://www.codefoundry.dev/' property='og:url'/>
        <meta content='Tutorials for Java, Java 8, Spring, Spring Cloud, Spring Boot, React JS, Redux, Next.JS' property='og:description'/>
        <meta content='Gaurav Rai Mazra' name='Author'/>
        <meta content='https://www.codefoundry.dev/' property='og:url'/>
        <meta content='https://www.codefoundry.dev/favicon.ico' property='og:image'/>
      </Head>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
    )
  }
}
// _app.tsx


import React from 'react';
import { AppProps } from 'next/app';
import { Provider } from 'react-redux';
import { store } from '../redux/store';

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <React.StrictMode>
      <Provider store={store}>
        <Component {...pageProps} />
      </Provider>
    </React.StrictMode>
  )
}

export default MyApp;

Creating first page

Let's create our first page index.tsx under src/pages directory.

/* Line 1 */
interface IServerProps {
  bloggerPosts: {
    allTags: string[]
    posts: IBlogPost[]
  }
}

export default (props: IServerProps) => {
  /* Line 2 */ const dispatch = useDispatch();
  useEffect(() => {
    /* Line 3 */ dispatch(setPostsAsync(props.bloggerPosts));
  }, [dispatch, props.bloggerPosts])
  return (<App />)
}

/* Line 4 */ export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext<any>) => {
  /* Line 5 */const bloggerPosts = await BloggerService.getAllPosts();
  return {
    props: {
      bloggerPosts
    }
  }
} 

At Line 1, we have defined type of prop field of this functional component. At line 2, We are using useDispatch hook from redux to get reference of dispatch function. Inside useEffect hook, at line 3, we are dispatching the bloggerPosts that were computed on server-side by Next.js(Line 4).

At Line 4, we are defining getServerSideProps function which gets executed on every request by Next.js on the server-side and the result is passed onto this functional component.

At Line 5, we are calling BloggerService's getAllPosts function which is retrieving the posts from blogger(http://codefoundry.dev)'s feed. Let's create this service(BloggerService.ts) as well under src/service.

/* Line 1 */ declare type BloggerEntry = {
  id: {
    $t: string
  },
  updated: {
    $t: string
  },
  published: {
    $t: string
  },
  category: Array<{scheme: string, term: string}>,
  title: {
    $t: string
  },
  summary: {
    $t: string
  },
  author: Array<{name: { $t: string }}>,
  link: Array<{ rel: string, href: string }>
}

const getAllPosts = async() => {
  /* Line 2 */ const response = await fetch('https://www.blogger.com/feeds/5554118637855932326/posts/summary?alt=json&start-index=1&max-results=100')
  const result = await response.json();
  const categories = result?.feed?.category ?? [];
  const allTags = (categories as Array<{term: string}>).map(category => category.term)
  const entries = result?.feed?.entry ?? [];
  const posts = (entries as Array<BloggerEntry>).map(entry => {
    const id = entry.id.$t;
    const datePublishedOrUpdated = entry.updated.$t || entry.published.$t;
    const tags = entry.category.map(cat => cat.term);
    const title = entry.title.$t;
    const content = entry.summary.$t;
    const author = entry.author.map(a => a.name.$t).join(', ')
    const postLink = entry.link.find(l => l.rel === 'alternate');
    const postUrl = !!postLink ? postLink.href : '';

    /* Line 3 */ return {
      id,
      tags,
      title,
      content,
      author,
      postUrl,
      postedOn: datePublishedOrUpdated
    }
  })
  return { allTags, posts };
}

export default { getAllPosts }

At Line 1, we declared a type BlogEntry which refers to entry sent by the blogger's feed. At Line 2, we are using fetch api to retrieve summary feed from blogger(http://codefoundry.dev) and we are transforming and returning it to the type that our reducer store understands (At Line 3).

Cleanup App.tsx and BlogPosts.tsx

Earlier, we hard-coded posts(POSTS array) in App.tsx and were passing to BlogPosts component. Let's clean it up.

// App.tsx
function App() {
  return (
    <>
      <div className={styles['App-Container']}>
        <BlogPosts />
      </div>
    </>
  );
}

export default App;
// BlogPosts.tsx
function BlogPosts() {
  return (
    <div className={styles["blog-container"]}>
      <BlogPost/>
      <BlogListing/>
    </div>
  );
}

Let's run the application with command npm run dev.

That's it :). You can download the full code from github.

Recap

In this post, we first added required set of libraries (next and @types/next). Then, we added scripts to build, run and start project with next.js. Then, we did basic setup for next.js application e.g. Setting up _document.tsx and _app.tsx. Then, we created our first page index.tsx and created getServerSideProps method for server-side rendering. At last, we cleaned up App.tsx and BlogPosts.tsx file and ran the application.

What's next?

In the next post, we will use Next.js to generate static site along with Dynamic routing in static site. So, stay tuned!

In the previous post, we created a blog post application with React and managed local state with useState hook. We will extend the same application and will introduce Redux and react-redux library for state management and @reduxjs/toolkit for opinionating setting up the redux store and creating selector function on state.

Adding required libraries

Run npm i --save @reduxjs/toolkit react-redux @types/react-redux from root of the project to add required set of libraries for this post.

Which new functions we will be using in this example?

  • configureStore from @reduxjs/toolkit
  • createSlice from @reduxjs/toolkit
  • useDispatch from react-redux
  • useSelctor from react-redux
  • useEffect from react

@reduxjs/toolkit: configureStore

This function provides a convenient abstraction over createStore function of redux library. It adds good defaults to the store for better experience(e.g. DevTools, Redux-Thunk for async actions).

@reduxjs/toolkit: createSlice

This function accepts an initial state, list of reducers and a 'slice name' and automatically generates action creators and action types for the reducer. You can also pass extraReducers to it for handling other complex reductions.

react-redux: useDispatch

This hook let's you access dispatch function of redux.

react-redux: useSelector

This Hook let's you tap on redux state and filter content. It takes selector function and optional equality function for state. If you require complex selector (memoized), then reselect library is a good choice. In this example, we will use simple selector on state.

React: useEffect

This hook is a combination of componentDidMount, componentDidUpdate and componentWillUnmount lifecycle methods of React. This hooks accepts the imperative function which can return the cleanup function as return statement; which will get executed on before every re-render. You can read a detailed post in React docs.

Configuring redux store

Create store.ts under src/redux folder.

import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit';
import blogPostsReducer from './reducer/blogPostsSlice';

export const store = configureStore({
  reducer: {
    blogPosts: blogPostsReducer,
  },
});

// Defining the root state
export type RootState = ReturnType<typeof store.getState>;
export type AppThunk<ReturnType = void> = ThunkAction<
  ReturnType,
  RootState,
  unknown,
  Action<string>
>;

We are passing blogPostsReducer in the reducer parameter to configureStore function. We will be creating this reducer shorlty. Also, We have defined two types; one is RootState which defines the type of Root reducer and other is Appthunk which defines the ThunkAction (Async function).

Creating reducer for blog posts

Create blogPostsSlice.ts under src/redux/reducer folder.

Let's first add interface BlogPostsState which defines the state this slice will hold.

interface BlogPostsState {
  posts: IBlogPost[]
}

// Initial state of the reducer
const initialState: BlogPostsState = {
  posts: []
}

We will use createSlice function from @reduxjs/toolkit.

const blogPostsSlice = createSlice({
  name: 'blogPosts',
  initialState,
  reducers: {
   // We will soon pass the reducers here
  }
});

In the previous post, we managed all the local state in the BlogPosts.tsx component. We will start by moving `posts` stored in the local state to redux state. Define the setPosts reducer function under reducers property of the slice that we are creating.

const blogPostsSlice = createSlice({
  name: 'blogPosts',
  initialState,
  reducers: {
    setPosts: (state, action: PayloadAction<IBlogPost[]>) => {
      /*1.*/state.posts = action.payload
      // Alternate solution
      // return { ...state, posts: action.payload }
    }
  }
});

//actions froms slice
/*Line 2*/const { setPosts } = blogPostsSlice.actions;

// Async action functions
/*Line 3*/const setPostsAsync = (posts: IBlogPost[]): AppThunk => dispatch => {
  setTimeout(() => {
    dispatch(setPosts(posts))
  }, 500)
}

// Selector functions
/*Line 4*/ const selectPosts = (state: RootState) => state.blogPosts.posts;

/*Line 5*/export { selectPosts };

//action functions
/*Line 6*/export { setPosts, setPostsAsync };

// reducer
/*Line 7*/ export default blogPostsSlice.reducer;

At line 1, we are mutating the redux state directly. Don't worry, the state passed in the function as first argument is not the actual redux state but proxy on it. It uses immer library under the hood to manage and update the state(recreate). Alternatively, you can return your state object but can't do both(Mutating state and return new state object).

At line 2, we are getting actions created by createSlice function.

At line 3, we are creating async function to update posts. We are mimicking the async nature by setTimeout method. But, in real world, it would be replaced by API call to backend.

At Line 4, we have created selector function for posts. We are exporting selector function, actions and reducer at line 5, 6 and 7 respectively.

Update BlogPosts.tsx component

import { useDispatch, useSelector } from 'react-redux';
import { selectPosts, setPostsAsync } from '../redux/reducer/blogPostsSlice';

Use useEffect hook to update redux state with posts.

function BlogPosts(props: IBlogPostsProps) {
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(setPostsAsync(props.posts))
  }, [ props.posts, dispatch ]);


  ...
}

Replace local state management for posts with selecting state from redux store

/*Remove this line*/ //const [ posts, setPosts ] = useState(props.posts)
/*Add this line*/ const posts = useSelector(selectPosts);

Update onSearch function and replace it setPosts method with dispatch method.

function onSearch() {
  if (searchText !== '') {
    const foundPosts = props.posts.filter(filterPost)
    setShowingPost(findFirstPost(foundPosts))
    dispatch(setPostsAsync(foundPosts))
  } else {
    setShowingPost(findFirstPost(props.posts))
    dispatch(setPostsAsync(props.posts))
  }
}

Update index.tsx

Update index.tsx and wrap component with Provider component.

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);

Now, run the application with npm run start command. The application will load as before but only change is we are reffering posts from redux store.

Update BlogPosts.tsx and replace all the local state with redux management state.

interface IBlogPostsProps {
  posts: Array<IBlogPost>
}


function BlogPosts(props: IBlogPostsProps) {
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(setPostsAsync(props.posts))
    dispatch(setShowingPostsAsync(props.posts && props.posts.length > 0 ? props.posts[0].id : 0))
  }, [ props.posts, dispatch ]);

  function findFirstPost(posts: Array<IBlogPost>) : IBlogPost | null {
    return posts && posts.length > 0 ? posts[0] : null;
  }

  const posts = useSelector(selectPosts);
  const showingPost = useSelector(selectShowingPost);
  const searchText = useSelector(selectSearchText);
  const selectedSearchOn = useSelector(selectSelectedSearchOn);

  function onBlogPostLinkClick(id: number): void {
    dispatch(setShowingPostsAsync(id));
  }
  
  function onChangeHandler(value: string, searchType: SearchType) : void {
   if (SearchType.SEARCH_TEXT === searchType) {
     dispatch(setSearchText(value));
   } else {
     dispatch(setSelectedSearchOn(value === SearchOnFields.TAG ? SearchOnFields.TAG : SearchOnFields.TITLE))
   }
  }

  function isMatched(value: string) {
    return value.toLowerCase().includes(searchText.toLowerCase())
  }

  function filterPost(post: IBlogPost) {
    if (selectedSearchOn === 'title') {
      return isMatched(post.title)
    } else {
      return post.tags.some(isMatched)
    }
  }

  function onSearch() {
    if (searchText !== '') {
      const foundPosts = props.posts.filter(filterPost)
      dispatch(setShowingPostsAsync(findFirstPost(foundPosts)?.id ?? 0))
      dispatch(setPostsAsync(foundPosts))
    } else {
      dispatch(setPostsAsync(props.posts))
      dispatch(setShowingPostsAsync(findFirstPost(props.posts)?.id ?? 0))
    }
  }

  return (
    <div className="blog-container">
      <BlogListing
        showingPost={showingPost?.id ?? 0}
        blogPosts={posts.map(post => { return {id: post.id, title: post.title }})}
        onClick={onBlogPostLinkClick}
        searchText={searchText}
        onSearchChange={onChangeHandler}
        onSearchButtonClick={onSearch}
        selectedSearchOn={selectedSearchOn}
      />
      {!!showingPost ? <BlogPost post={showingPost}/>: null }
    </div>
  );
}

export default BlogPosts;

Refactoring components

Before introducing redux, we managed whole state in the top level component aka BlogPosts.tsx and were passing the various variables to the child components. After introducing redux for state management, we don't require to pass on the various variables to child components. They can query it directly from the redux store using selector functions. Let's update all the components.

Updating BlogPost.tsx

function BlogPost() {
  /*Line 1*/const post = useSelector(selectShowingPost);
  return !!post ? (
    <div className='blog-post'>
      <div className='blog-post-title'>{post.title}</div>
      <div className='blog-post-body'>{post.content}</div>
      <div className='blog-post-footer'>
        <div className='blog-author'>{`By ${post.author} at ${post.postedOn}`}</div>
        <div className='blog-tags'>
          <div key='tags-label'>Tags: </div>
          {post.tags.map(tag => <div key={tag}>{tag}</div>)}
        </div>
      </div>
    </div>
  ) : (<></>);
}

export default BlogPost;

Explanation: We have removed the props and is using useSelector hook to get the current selectedPost for showing.

Updating BlogSearch.tsx

function BlogSearch() {
  const dispatch = useDispatch();

  /*Line 1*/const searchText = useSelector(selectSearchText);
  /*Line 2*/const selectedSearchOn = useSelector(selectSelectedSearchOn);

  function onSearchTextChange(event: ChangeEvent<HTMLInputElement>): void {
    /*Line 3*/dispatch(setSearchText(event.target.value));
  }

  function onSearchOnChange(event: ChangeEvent<HTMLSelectElement>): void {
    /*Line 4*/dispatch(setSelectedSearchOn(event.target.value === SearchOnFields.TAG ? SearchOnFields.TAG: SearchOnFields.TITLE));
  }

  return(
    <div className="blog-search-container">
      <div className='blog-search-title'>Search Blog</div>
      <div className='blog-search-body'>
        <input type="text" className="form-control" autoComplete="off" value={searchText ?? ''} onChange={onSearchTextChange}/>
        <select value={selectedSearchOn} className='form-control' onChange={onSearchOnChange}>
          <option value={SearchOnFields.TAG}>Tags</option>
          <option value={SearchOnFields.TITLE}>Title</option>
        </select>
        <button type="button" className="form-button" onClick={() => { /*Line 5*/dispatch(onSearchAsync()) }}>Search</button>
      </div>
    </div>
  );
}

export default BlogSearch;

Explanation: We have removed the props proeprty and type. At Line 1 and 2, we are using selector functions and useSelector hook to get searchText and selectedSearchOn from redux state respectively. At Line 3 and 4, we are using setSearchText and setSelectedSearchOn actions(redux) to update searchText and selectedSearchOn state in redux store respectively. At Line 5, we are calling onSearch action(blogPostsSlice) and updates the state in redux store for searchResults.

Update BlogListing.tsx

function BlogListing() {
  /*Line 1*/const blogPosts: IBlogPostListing[] = useSelector(selectPostsForListing);
  /*Line 2*/const showingPostId = useSelector(selectShowingPostId);

  const dispatch = useDispatch();

  return(
    <div className='blog-listing'>
      <BlogSearch/>
      <ul className="blog-posts">
        {
          blogPosts.map(post => <li className={showingPostId === post.id ? 'active' : ''} key={post.id} onClick={() => /*Line 3*/dispatch(setShowingPostsAsync(post.id))}>{post.title}</li>)
        }
      </ul>
    </div>
  );
}

export default BlogListing;

We have removed the props from BlogListing and also deleted IBlogListing type. At Line 1 and 2, we are getting state directly using selector function for posts and currently showing Blog post id respectively. At Line 3, we are triggering setShowingPostsAsync action created in blogPostsSlice.ts.

Updating BlogPosts.tsx

function BlogPosts(props: IBlogPostsProps) {
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(setPostsAsync(props.posts))
    dispatch(setShowingPostsAsync(props.posts && props.posts.length > 0 ? props.posts[0].id : 0))
  }, [ props.posts, dispatch ]);

  return (
    <div className="blog-container">
      <BlogListing/>
      <BlogPost/>
    </div>
  );
}

export default BlogPosts;

We have removed all the local state and function which we were passing to the children components. Now, we only are using React useEffect hook to update the redux state with posts.

That's it. :). You can get the full source code of this example from github.

Recap

In this post, we first added new libraries (react-redux, @reduxjs/toolkit). We explained few specific functions that we will be using in this example. Then, we created store.ts, blogPostsSlice.ts and started with replacing local state of posts from BlogPosts.tsx. Then, we replaced searchText, selectedSearchOn and showingPost from local state to redux state. We also added few selector functions. At last, we refactored our example and removed most of the method and variable reference from the top level component BlogPosts.tsx and added those in the respective components.

What's next?

In the next post, we will introduce server side rendering with Next.js. So, stay tuned!

Introduction

React was first introducted to general public in May 2013; roughly three years after the first release of Angular JS (October 2010). Soon, it picked up the momentum and now is the highest stared(~150K) and forked(29.2K) repository on Github. The positive point of React with its contemporary libraries was the backward compatibility in all the released versions. It started as a class based library (extending React.Component) to pure functional library with React Hooks; still keeping backward compatibility. Now, new features include asyncronous rendering with Suspense. React's ecosystem is very vast with lots of frameworks available to choose from. We will start with building first simple a.ka. Welcome react application and then build full-stack application with React, Redux, reselect, Next.JS, express JS and Node.JS. So, stay tuned :)

Building your first React application

You can create React application with project like create-react-app or can create customize project intialiting the project with npm and then pick and choose libraries of your choice. In this post, we will use create-react-app.

create-react-app conviently configures the tools like webpack, babel and testing libraries, so that you can concentrate purely on application code.

npx create-react-app my-first-react-app

npx is a package runner tool that comes with npm 5.2+ and higher.

This single line of code will setup Javascript based project, configures webpack, babel and testing libraries.

my-first-react-app
├── README.md
├── node_modules
├── package.json
├── .gitignore
├── public
│   ├── favicon.ico
│   ├── index.html
│   └── manifest.json
└── src
    ├── App.css
    ├── App.js
    ├── App.test.js
    ├── index.css
    ├── index.js
    ├── logo.svg
    └── serviceWorker.js
    └── setupTests.js

It will also configure commands in package.json to start, build, test and eject (A command to remove transitive dependencies of webpack, babel, testing libraries and copies directly to package.json so that you can customize accordingly).

Let's run the application with npm run start and visit localhost:3000 on browser.

Creating first React component

Let's start with creating a component.

Create a new file Welcome.js and Welcome.css under src folder.

Add following lines to Welcome.js

import React from 'react';
import './Welcome.css';

function Welcome() {
  return <div className='welcome'>Welcome! My first react app</div>
}

export default Welcome;

Here, we have created a functional component which is equivalent to extending React.Component class and adding render function in it.

import React from 'react';
import './Welcome.css';

class Welcome extends React.Component {
  render() {
    return <div className='welcome'>Welcome! My first react app</div>
  }
}

export default Welcome;

Now, the first React component; let's add it to App.js

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <Welcome />
      </header>
    </div>
  );
}

Now, go to localhost:3000 and you will see the component loaded.

Creating Typescript based first React application

Typescript is a typed superset of Javascript which compiles to plain Javascript. It provides the type safety to Javascript. create-react-app provides convenient way to change template for generating React skeleton project. Just pass the template parameter with value as follows.

npx create-react-app my-first-react-app --template typescript

Adding first typed component

Create a new file Welcome.tsx and Welcome.css under src folder.

Add following lines to Welcome.tsx

import React from 'react';
import './Welcome.css';

interface IWelcomeProps {
  message?: string
}

function Welcome(props: IWelcomeProps) {
  const message = props?.message ?? 'Welcome! My first React app with Typescript.'
  return (<div className='welcome'>{message}</div>);
}

export default Welcome;

We have defined the interface IWelcomeProps with single optional field message. In the functional component, we have used the Nullish coalescing added in Typescript 3.7.

Let's add this component to App.tsx

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <Welcome />
        <Welcome message="Welcome Reader! My first react app with Typescript."/>
      </header>
    </div>
  );
}

We have added Welcome twice; with and without message field. The output after running the application will look like this.

Recap

We created our first React application using create-react-app project. We added first React component Welcome.js and Welcome.tsx in Javascript and Typescript based projects respectively.

What's next?

In the next post, we will build a BlogPost application using React's functional component and React hooks. We will use useState hook for state management. So, stay tuned!