One place for hosting & domains

      Manage

      How To Use Migrations to Create and Manage Database Tables in Laravel



      Part of the Series:
      How To Build a Links Landing Page in PHP with Laravel and Docker Compose

      Laravel is an open-source PHP framework that provides a set of tools and resources to build modern PHP applications. In this project-based tutorial series, you’ll build a Links Landing Page application with the Laravel framework, using a containerized PHP development environment managed by Docker Compose.

      At the end, you’ll have a one-page website built with Laravel and managed via Artisan commands where you can share relevant links to an audience on social channels and presentations.

      Laravel database migrations allow developers to quickly bootstrap, destroy, and recreate an application’s database, without the need to log into the database console or run any SQL queries.

      In this guide, you’ll create a database migration to set up the table where you’ll save the application links. In order to do that, you’ll use the Artisan command-line tool that comes with Laravel by default. At the end, you will be able to destroy and recreate your database tables as many times as you want, using only artisan commands.

      To get started, first make sure you’re in the application’s root directory and your Docker Compose development environment is up and running:

      • cd ~/landing-laravel
      • docker-compose up -d

      Output

      landing-laravel_app_1 is up-to-date landing-laravel_nginx_1 is up-to-date landing-laravel_db_1 is up-to-date

      Next, create a database migration to set up the links table. Laravel Migrations allow developers to programmatically create, update, and destroy database tables, working as a version control system for your database schema.

      To create a new migration, you can run the make:migration Artisan command and that will bootstrap a new class on your Laravel application, in the database/migrations folder. This class will contain a default boilerplate code.

      Remember to use docker-compose exec app to run the command on the app service container, where PHP is installed:

      • docker-compose exec app php artisan make:migration create_links_table

      Output

      Created Migration: 2020_11_18_165241_create_links_table

      Notice that the migration name is generated based on the current date and time, and the name provided as argument to the make:migration command. For that reason, your migration file name will differ slightly.

      Open the generated migration class using your editor of choice:

      • nano database/migrations/2020_11_18_165241_create_links_table

      Next, update the up method to include the table columns you’ll need to store the app data.

      Replace the current content of your migration class with the following code. The highlighted values are the only lines that need adding, so if you prefer, you can also only copy those highlighted lines and include them into your Schema::create definition:

      database/migrations/2020_10_12_171200_create_links_table.php

      <?php
      
      use IlluminateDatabaseMigrationsMigration;
      use IlluminateDatabaseSchemaBlueprint;
      use IlluminateSupportFacadesSchema;
      
      class CreateLinksTable extends Migration
      {
          /**
           * Run the migrations.
           *
           * @return void
           */
          public function up()
          {
              Schema::create('links', function (Blueprint $table) {
                  $table->id();
                  $table->string('url', 200);
                  $table->text('description');
                  $table->boolean('enabled')->default(true);
                  $table->timestamps();
              });
          }
      
          /**
           * Reverse the migrations.
           *
           * @return void
           */
          public function down()
          {
              Schema::dropIfExists('links');
          }
      }
      

      In addition to the default fields that are included in the table definition that is automatically generated with the Artisan command, you’re including three new fields in this table:

      • url : A string field to save the link URL.
      • description : A text field to save the link description.
      • enabled : A field to store the state of the link, whether it’s enabled or not. The boolean Schema type will generate a tinyint unsigned field to store a value of either 0 of 1.

      Save your migration file when you’re done adding these fields. Next, run the migration with:

      • docker-compose exec app php artisan migrate

      Output

      Migration table created successfully. Migrating: 2014_10_12_000000_create_users_table Migrated: 2014_10_12_000000_create_users_table (152.46ms) Migrating: 2014_10_12_100000_create_password_resets_table Migrated: 2014_10_12_100000_create_password_resets_table (131.12ms) Migrating: 2019_08_19_000000_create_failed_jobs_table Migrated: 2019_08_19_000000_create_failed_jobs_table (101.06ms) Migrating: 2020_11_18_165241_create_links_table Migrated: 2020_11_18_165241_create_links_table (60.20ms)

      You’ll notice that other migrations were also executed along with the create_links_table. That is because the default Laravel installation comes with migrations for users (with a users table and a password_resets table) and for queued jobs (with a failed_jobs table). Because our demo application won’t use these features, it is safe to remove those migrations now; however, you may also opt to leave them in place if you are working on an application of your own and you plan on developing it further. All migration files are located at database/migrations in the app’s root folder.

      For more detailed information on database migrations, please refer to our guide on How To Use Database Migrations and Seeders to Abstract Database Setup in Laravel.

      In the next part of this series, you’ll create a custom Artisan command to list, insert, and delete entries in the app’s links table.



      Source link

      How To Create Artisan Commands To Manage Database Records in Laravel



      Part of the Series:
      How To Build a Links Landing Page in PHP with Laravel and Docker Compose

      Laravel is an open-source PHP framework that provides a set of tools and resources to build modern PHP applications. In this project-based tutorial series, you’ll build a Links Landing Page application with the Laravel framework, using a containerized PHP development environment managed by Docker Compose.

      At the end, you’ll have a one-page website built with Laravel and managed via Artisan commands where you can share relevant links to an audience on social channels and presentations.

      If you followed along with this series so far, your database tables should be all set. However, you still need to implement a way to let users insert new entries in the links table.

      To limit the scope of this series while also making the application fully-functional, you’ll set up Artisan commands to create and delete links in the database. Artisan is the command line tool that comes with Laravel, offering a number of utilities to speed up the development process, from generating boilerplate code to deleting and re-creating the application’s database.

      Using the command line interface to manage your application can be an alternative to web forms and secured areas, since it requires a user to be logged on the server in order to execute such commands instead of being authenticated from a browser. If you decide later on to create a secured area for your application, you can create web forms to allow a registered user to submit a new link to the database.

      Artisan commands are often used to perform application tasks that should run in the background, either manually or automatically via a scheduling mechanism such as Crontab. They can also be used to facilitate prototyping new application features that need to be configured dynamically, depending on input from an authorized user.

      To get started, create a new Artisan command using the make:command helper:

      • docker-compose exec app php artisan make:command LinkNew

      Output

      Console command created successfully.

      This will create a file named LinkNew.php, located at the app/Console/Commands directory. In this class, which extends from the IlluminateConsoleCommand parent class, you’ll need to implement a handle method that will be executed when this command is called. To define the signature of the command, you’ll set the $signature protected property to link:new.

      Open the new file using your text or code editor of choice. Here, we’ll use nano:

      • nano app/Console/Commands/LinkNew.php

      A few different things will need to happen in the handle method so that you are able to save a new link to the database. First, you’ll prompt for the user’s input in order to obtain the link URL.

       $url = $this->ask('Link URL:');
      

      Then, you’ll use the filter_var function to validate that the input obtained from the user is a valid URL. If the link is invalid, you’ll show an error and exit the application with status code 1, which means the application exited in error.

              if (!filter_var($url, FILTER_VALIDATE_URL)) {
                  $this->error("Invalid URL. Exiting...");
                  return 1;
              }
      

      If the link is valid, you’ll continue and ask for the link description using the same method as before.

       $description = $this->ask('Link Description:');
      

      You’ll then ask for a final confirmation that all data is correct, using the confirm helper. If the user confirms, the link is finally inserted in the database. You’ll use the Link Eloquent model created in a previous part of this series to interact with the database.

              $this->info("New Link:");
              $this->info($url . ' - ' . $description);
      
              if ($this->confirm('Is this information correct?')) {
                  $link = new Link();
                  $link->url = $url;
                  $link->description = $description;
                  $link->save();
      
                  $this->info("Saved.");
              }
      

      The application exits with a 0, representing a success status (0 errors).

      return 0;
      

      The following code contains the full implementation of these steps. Replace the current content in your LinkNew class with:

      app/Console/Commands/LinkNew.php

      <?php
      
      namespace AppConsoleCommands;
      
      use AppModelsLink;
      use IlluminateConsoleCommand;
      use IlluminateSupportFacadesDB;
      
      class LinkNew extends Command
      {
          /**
           * The name and signature of the console command.
           *
           * @var string
           */
          protected $signature="link:new";
      
          /**
           * The console command description.
           *
           * @var string
           */
          protected $description = 'Create a New Link';
      
          /**
           * Create a new command instance.
           *
           * @return void
           */
          public function __construct()
          {
              parent::__construct();
          }
      
          /**
           * Execute the console command.
           *
           * @return int
           */
          public function handle()
          {
              $url = $this->ask('Link URL:');
      
              if (!filter_var($url, FILTER_VALIDATE_URL)) {
                  $this->error("Invalid URL. Exiting...");
                  return 1;
              }
      
              $description = $this->ask('Link Description:');
      
              $this->info("New Link:");
              $this->info($url . ' - ' . $description);
      
              if ($this->confirm('Is this information correct?')) {
                  $link = new Link();
                  $link->url = $url;
                  $link->description = $description;
                  $link->save();
      
                  $this->info("Saved.");
              }
      
              return 0;
          }
      }
      

      Save and close the file when you’re done.

      To execute the command and insert a new link in the database, run:

      • docker-compose exec app php artisan link:new

      Output

      Link URL:: > https://digitalocean.com/community Link Description:: > DigitalOcean Community New Link: https://digitalocean.com/community - DigitalOcean Community Is this information correct? (yes/no) [no]: > yes Saved.

      Feel free to add a few more links if you want to.

      Next, you’ll need to create a new Artisan command to show the list of all links.You can call it link:list. Create the new command with:

      • docker-compose exec app php artisan make:command LinkList

      Open the command class using your text or code editor of choice:

      • nano app/Console/Commands/LinkList.php

      Within the handle method of this command, you’ll query for all rows in the links table. You can use the Link model to access the underlying database query methods that Eloquent provides. To exhibit the results nicely in the command line, you can use the table output helper:

              $headers = [ 'id', 'url', 'description' ];
              $links = Link::all(['id', 'url', 'description'])->toArray();
              $this->table($headers, $links);
      
              return 0;
      

      The following code contains the full implementation of the link:list command. Replace the content in your LinkList.php file with :

      app/Console/Commands/LinkList.php

      <?php
      
      namespace AppConsoleCommands;
      
      use AppModelsLink;
      use IlluminateConsoleCommand;
      
      class LinkList extends Command
      {
          /**
           * The name and signature of the console command.
           *
           * @var string
           */
          protected $signature="link:list";
      
          /**
           * The console command description.
           *
           * @var string
           */
          protected $description = 'List links saved in the database';
      
          /**
           * Create a new command instance.
           *
           * @return void
           */
          public function __construct()
          {
              parent::__construct();
          }
      
          /**
           * Execute the console command.
           *
           * @return int
           */
          public function handle()
          {
              $headers = [ 'id', 'url', 'description' ];
              $links = Link::all(['id', 'url', 'description'])->toArray();
              $this->table($headers, $links);
      
              return 0;
          }
      }
      

      Save and close the file when you are done.

      To run this command and show a list of all links already inserted in the linkstable, run:

      • docker-compose exec app php artisan link:list

      Output

      +----+------------------------------------+--------------+ | id | url | description | +----+------------------------------------+--------------+ | 1 | https://digitalocean.com/community | DO Community | | 2 | https://laravel.com | Laravel | +----+------------------------------------+--------------+

      Finally, you’ll create a command to delete links:

      • docker-compose exec app php artisan make:command LinkDelete

      Output

      Console command created successfully.

      Open the new file using your text or code editor of choice:

      • nano app/Console/Commands/LinkDelete.php

      You can name this command link:delete. To know which link must be deleted, you’ll need to require that users provide an additional argument when calling the command: the ID of the link. This is also set within the $signature variable, which defines how your command is called and what arguments, mandatory or not, should be provided:

      protected $signature="link:delete {link_id}";
      

      The handle method for this command will implement a few different instructions. First, you’ll obtain the Link ID that should have been provided within the command call.

      $link_id = $this->argument('link_id');
      

      Then, you’ll obtain the referenced link from the database, using the Eloquent method find that is available through your Link model.

      $link = Link::find($link_id);
      

      When the find method doesn’t find a database record with that ID, it will return null. You’ll check if that is the current value contained in the $link variable, and return an error in that case. The program will exit in error (code 1).

              if ($link === null) {
                  $this->error("Invalid or non-existent link ID.");
                  return 1;
              }
      

      When $link is not null, the command continues execution. You then use the confirm helper to ask for a user confirmation.

      if ($this->confirm('Are you sure you want to delete this link? ' . $link->url)) {
          // deletes link
      }
      

      When the user confirms the action by typing yes and hitting ENTER, you’ll call the delete method from the Link Eloquent model to delete the specified link from the database.

                  $link->delete();
                  $this->info("Link deleted.");
      

      The following code contains the full implementation for the list:delete command. Replace the content in your LinkDelete.php file with the following:

      app/Console/Commands/LinkDelete.php

      <?php
      
      namespace AppConsoleCommands;
      
      use AppModelsLink;
      use IlluminateConsoleCommand;
      use IlluminateSupportFacadesDB;
      
      class LinkDelete extends Command
      {
          /**
           * The name and signature of the console command.
           *
           * @var string
           */
          protected $signature="link:delete {link_id}";
      
          /**
           * The console command description.
           *
           * @var string
           */
          protected $description = 'Deletes a link from the database.';
      
          /**
           * Create a new command instance.
           *
           * @return void
           */
          public function __construct()
          {
              parent::__construct();
          }
      
          /**
           * Execute the console command.
           *
           * @return int
           */
          public function handle()
          {
              $link_id = $this->argument('link_id');
              $link = Link::find($link_id);
      
              if ($link === null) {
                  $this->error("Invalid or non-existent link ID.");
                  return 1;
              }
      
              if ($this->confirm('Are you sure you want to delete this link? ' . $link->url)) {
                  $link->delete();
                  $this->info("Link deleted.");
              }
      
              return 0;
          }
      }
      

      Save and close the file when you’re done.

      Now when you want to delete a link from your links table, you’ll first need to obtain the link’s ID with artisan link:list, as demonstrated earlier on. Once you know the ID of a link, you can run the artisan link:delete command with:

      • docker-compose exec app php artisan link:delete LINK_ID

      Output

      Are you sure you want to delete this link? https://laravel.com (yes/no) [no]: > yes Link deleted.

      You’re now able to insert, list, and delete links in the application’s database, using Artisan commands executed from a command-line interface. In the next part of this series, you’ll set up the front end of your application using Blade templates and the Bulma CSS framework.



      Source link

      How To Manage State in React with Redux


      The author selected Creative Commons to receive a donation as part of the Write for DOnations program.

      Introduction

      Redux is a popular data store for JavaScript and React applications. It follows a central principle that data binding should flow in one direction and should be stored as a single source of truth. Redux gained popularity because of the simplicity of the design concept and the relatively small implementation.

      Redux operates according to a few concepts. First, the store is a single object with fields for each selection of data. You update the data by dispatching an action that says how the data should change. You then interpret actions and update the data using reducers. Reducers are functions that apply actions to data and return a new state, instead of mutating the previous state.

      In small applications, you may not need a global data store. You can use a mix of local state and context to manage state. But as your application scales, you may encounter situations where it would be valuable to store information centrally so that it will persist across routes and components. In that situation, Redux will give you a standard way to store and retrieve data in an organized manner.

      In this tutorial, you’ll use Redux in a React application by building a bird watching test application. Users will be able to add birds they have seen and increment a bird each time they see it again. You’ll build a single data store, and you’ll create actions and reducers to update the store. You’ll then pull data into your components and dispatch new changes to update the data.

      Prerequisites

      • You will need a development environment running Node.js; this tutorial was tested on Node.js version 10.22.0 and npm version 6.14.6. To install this on macOS or Ubuntu 18.04, follow the steps in How to Install Node.js and Create a Local Development Environment on macOS or the Installing Using a PPA section of How To Install Node.js on Ubuntu 18.04.

      • A React development environment set up with Create React App, with the non-essential boilerplate removed. To set this up, follow Step 1 — Creating an Empty Project of the How To Manage State on React Class Components tutorial. This tutorial will use redux-tutorial as the project name.

      • You will be using React components, Hooks, and forms in this tutorial, including the useState Hook and custom Hooks. You can learn about components and Hooks in our tutorials How To Manage State with Hooks on React Components and How To Build Forms in React.

      • You will also need a basic knowledge of JavaScript, HTML, and CSS, which you can find in our How To Build a Website With HTML series, How To Build a Website With CSS series, and in How To Code in JavaScript.

      Step 1 — Setting Up a Store

      In this step, you’ll install Redux and connect it to your root component. You’ll then create a base store and show the information in your component. By the end of this step, you’ll have a working instance of Redux with information displaying in your components.

      To start, install redux and react-redux. The package redux is framework agnostic and will connect your actions and reducers. The package react-redux contains the bindings to run a Redux store in a React project. You’ll use code from react-redux to send actions from your components and to pull data from the store into your components.

      Use npm to install the two packages with the following command:

      • npm install --save redux react-redux

      When the component is finished installing, you’ll receive output like this. Your output may be slightly different:

      Output

      ... + redux@4.0.5 + react-redux@7.2.1 added 2 packages from 1 contributor, updated 1 package and audited 1639 packages in 20.573s

      Now that you have the packages installed, you need to connect Redux to your project. To use Redux, you’ll need to wrap your root components with a Provider to ensure that the store is available to all child components in the tree. This is similar to how you would add a Provider using React’s native context.

      Open src/index.js:

      Import the Provider component from the react-redux package. Add the Provider to your root component around any other components by making the following highlighted changes to your code:

      redux-tutorial/src/index.js

      import React from 'react';
      import ReactDOM from 'react-dom';
      import './index.css';
      import App from './components/App/App';
      import * as serviceWorker from './serviceWorker';
      import { Provider } from 'react-redux';
      
      ReactDOM.render(
        <React.StrictMode>
          <Provider>
            <App />
          </Provider>
        </React.StrictMode>,
        document.getElementById('root')
      );
      
      // If you want your app to work offline and load faster, you can change
      // unregister() to register() below. Note this comes with some pitfalls.
      // Learn more about service workers: https://bit.ly/CRA-PWA
      serviceWorker.unregister();
      

      Now that you have wrapped your components, it’s time to add a store. The store is your central collection of data. In the next step, you’ll learn to create reducers that will set the default values and update your store, but for now you will hard-code the data.

      Import the createStore function from redux, then pass a function that returns an object. In this case, return an object with a field called birds that points to an array of individual birds. Each bird will have a name and a views count. Save the output of the function to a value called store, then pass the store to a prop called store in the Provider:

      redux-tutorial/src/index.js

      import React from 'react';
      import ReactDOM from 'react-dom';
      import './index.css';
      import App from './components/App/App';
      import * as serviceWorker from './serviceWorker';
      import { Provider } from 'react-redux';
      import { createStore } from 'redux';
      
      const store = createStore(() => ({
        birds: [
          {
            name: 'robin',
            views: 1
          }
        ]
      }));
      
      ReactDOM.render(
        <React.StrictMode>
          <Provider store={store}>
            <App />
          </Provider>
        </React.StrictMode>,
        document.getElementById('root')
      );
      
      // If you want your app to work offline and load faster, you can change
      // unregister() to register() below. Note this comes with some pitfalls.
      // Learn more about service workers: https://bit.ly/CRA-PWA
      serviceWorker.unregister();
      

      Save and close the file. Now that you have some data, you need to be able to display it. Open src/components/App/App.js:

      • nano src/components/App/App.js

      Like with context, every child component will be able to access the store without any additional props. To access items in your Redux store, use a Hook called useSelector from the react-redux package. The useSelector Hook takes a selector function as an argument. The selector function will receive the state of your store as an argument that you will use to return the field you want:

      redux-tutorial/src/components/App/App.js

      import React from 'react';
      import { useSelector } from 'react-redux';
      import './App.css';
      
      function App() {
        const birds = useSelector(state => state.birds);
      
        return <></>
      }
      
      export default App;
      

      Since useSelector is a custom Hook, the component will re-render whenever the Hook is called. That means that the data—birds—will always be up to date.

      Now that you have the data, you can display it in an unordered list. Create a surrounding <div> with a className of wrapper. Inside, add a <ul> element and loop over the birds array with map(), returning a new <li> item for each. Be sure to use the bird.name as a key:

      redux-tutorial/src/components/App/App.js

      import React from 'react';
      import { useSelector } from 'react-redux'
      import './App.css';
      
      function App() {
        const birds = useSelector(state => state.birds);
      
        return (
          <div className="wrapper">
            <h1>Bird List</h1>
            <ul>
              {birds.map(bird => (
                <li key={bird.name}>
                  <h3>{bird.name}</h3>
                  <div>
                    Views: {bird.views}
                  </div>
                </li>
              ))}
            </ul>
          </div>
        );
      }
      
      export default App;
      

      Save the file. Once the file is saved, the browser will reload and you’ll find your bird list::

      List of birds

      Now that you have a basic list, add in the rest of the components you’ll need for your bird watching app. First, add a button to increment the views after the list of views:

      redux-tutorial/src/components/App/App.js

      import React from 'react';
      import { useSelector } from 'react-redux'
      import './App.css';
      
      function App() {
        const birds = useSelector(state => state.birds);
      
        return (
          <div className="wrapper">
            <h1>Bird List</h1>
            <ul>
              {birds.map(bird => (
                <li key={bird.name}>
                  <h3>{bird.name}</h3>
                  <div>
                    Views: {bird.views}
                    <button><span role="img" aria-label="add">➕</span></button>
                  </div>
                </li>
              ))}
            </ul>
          </div>
        );
      }
      
      export default App;
      

      Next, create a <form> with a single <input> before the bird list so a user can add in a new bird. Be sure to surround the <input> with a <label> and to add a type of submit to the add button to make sure everything is accessible:

      redux-tutorial/src/components/App/App.js

      import React from 'react';
      import { useSelector } from 'react-redux'
      import './App.css';
      
      function App() {
        const birds = useSelector(state => state.birds);
      
        return (
          <div className="wrapper">
            <h1>Bird List</h1>
            <form>
              <label>
                <p>
                  Add Bird
                </p>
                <input type="text" />
              </label>
              <div>
                <button type="submit">Add</button>
              </div>
            </form>
            <ul>
              {birds.map(bird => (
                <li key={bird.name}>
                  <h3>{bird.name}</h3>
                  <div>
                    Views: {bird.views}
                    <button><span role="img" aria-label="add">➕</span></button>
                  </div>
                </li>
              ))}
            </ul>
          </div>
        );
      }
      
      export default App;
      

      Save and close the file. Next, open up App.css to add some styling:

      • nano src/components/App/App.css

      Add some padding to the wrapper class. Then capitalize the h3 element, which holds the bird name. Finally, style the buttons. Remove the default button styles on the add <button> and then add a margin to the form <button>.

      Replace the file’s contents with the following:

      redux-tutorial/src/components/App/App.css

      
      .wrapper {
          padding: 20px;
      }
      
      .wrapper h3 {
          text-transform: capitalize;
      }
      
      .wrapper form button {
          margin: 10px 0;
          cursor: pointer;
      }
      
      .wrapper ul button {
          background: none;
          border: none;
          cursor: pointer;
      }
      

      Additionally, give each button a cursor of pointer, which will change the cursor when hovering over the button to indicate to the user that the button is clickable.

      Save and close the file. When you do the browser will refresh with your components:

      Bird watching app with form

      The buttons and form are not connected to any actions yet, and so can not interact with the Redux store. You’ll add the actions in Step 2 and connect them in Step 3.

      In this step, you installed Redux and created a new store for your application. You connected the store to your application using Provider and accessed the elements inside your components using the useSelector Hook.

      In the next step, you’ll create actions and reducers to update your store with new information.

      Step 2 — Creating Actions and Reducers

      Next, you’ll create actions to add a bird and to increment a view. You’ll then make a reducer that will update the information depending on the action type. Finally, you’ll use the reducers to create a default store using combineReducers.

      Actions are the message you send to the data store with the intended change. Reducers take those messages and update the shared store by applying the changes depending on the action type. Your components will send the actions they want your store to use, and your reducers will use actions to update the data in the store. You never call reducers directly, and there are cases where one action may impact several reducers.

      There are many different options for organizing your actions and reducers. In this tutorial, you’ll organize by domain. That means your actions and reducers will be defined by the type of feature they will impact.

      Create a directory called store:

      This directory will contain all of your actions and reducers. Some patterns store them alongside components, but the advantage here is that you have a separate point of reference for the shape of the whole store. When a new developer enters the project, they will be able to read the structure of the store at a glance.

      Make a directory called birds inside the store directory. This will contain the actions and reducers specifically for updating your bird data:

      Next, open up a file called birds.js so that you can start to add actions and reducers. If you have a large number of actions and reducers you may want to split them into separate files, such as birds.actions.js and birds.reducers.js, but when there are only a few it can be easier to read when they are in the same location:

      • nano src/store/birds/birds.js

      First, you are going to create actions. Actions are the messages that you send from a component to your store using a method called dispatch, which you’ll use in the next step.

      An action must return an object with a type field. Otherwise, the return object can include any additional information you want to send.

      Create a function called addBirds that takes a bird as an argument and returns an object containing a type of 'ADD_BIRD' and the bird as a field:

      redux-tutorial/src/store/birds/birds.js

      export function addBird(bird) {
        return {
          type: 'ADD_BIRD',
          bird,
        }
      }
      

      Notice that you are exporting the function so that you can later import and dispatch it from your component.

      The type field is important for communicating with reducers, so by convention most Redux stores will save the type to a variable to protect against misspelling.

      Create a const called ADD_BIRD that saves the string 'ADD_BIRD'. Then update the action:

      redux-tutorial/src/store/birds/birds.js

      const ADD_BIRD = 'ADD_BIRD';
      
      export function addBird(bird) {
        return {
          type: ADD_BIRD,
          bird,
        }
      }
      

      Now that you have an action, create a reducer that will respond to the action.

      Reducers are functions that will determine how a state should change based on actions. The actions don’t make changes themselves; the reducers will take the state and make changes based on actions.

      A reducer receives two arguments: the current state and the action. The current state refers to the state for a particular section of the store. Generally, the name of the reducer will match with a field in the store. For example, suppose you had a store shaped like this:

      {
        birds: [
          // collection of bird objects
        ],
        gear: {
          // gear information
        }
      }
      

      You would create two reducers: birds and gear. The state for the birds reducer will be the array of birds. The state for the gear reducer would be the object containing the gear information.

      Inside birds.js create a reducer called birds that takes state and action and returns the state without any changes:

      redux-tutorial/src/store/birds/birds.js

      const ADD_BIRD = 'ADD_BIRD';
      
      export function addBird(bird) {
        return {
          type: ADD_BIRD,
          bird,
        }
      }
      
      function birds(state, action) {
        return state;
      }
      

      Notice that you are not exporting the reducer. You will not use the reducer directly and instead will combine them into a usable collection that you will export and use to create your base store in index.js. Notice also that you need to return the state if there are no changes. Redux will run all the reducers anytime you dispatch an action, so if you don’t return state you risk losing your changes.

      Finally, since Redux returns the state if there are no changes, add a default state using default parameters.

      Create a defaultBirds array that will have the placeholder bird information. Then update the state to include defaultBirds as the default parameter:

      redux-tutorial/src/store/birds/birds

      const ADD_BIRD = 'ADD_BIRD';
      
      export function addBird(bird) {
        return {
          type: ADD_BIRD,
          bird,
        }
      }
      
      const defaultBirds = [
        {
          name: 'robin',
          views: 1,
        }
      ];
      
      function birds(state=defaultBirds, action) {
        return state;
      }
      

      Now that you have a reducer returning your state, you can use the action to apply the changes. The most common pattern is to use a switch on the action.type to apply changes.

      Create a switch statement that will look at the action.type. If the case is ADD_BIRD, spread out the current state into a new array and add the bird with a single view:

      redux-tutorial/src/store/birds/birds.js

      const ADD_BIRD = 'ADD_BIRD';
      
      export function addBird(bird) {
        return {
          type: ADD_BIRD,
          bird,
        }
      }
      
      const defaultBirds = [
        {
          name: 'robin',
          views: 1,
        }
      ];
      
      function birds(state=defaultBirds, action) {
        switch (action.type) {
          case ADD_BIRD:
            return [
              ...state,
              {
                name: action.bird,
                views: 1
              }
            ];
          default:
            return state;
        }
      }
      

      Notice that you are returning the state as the default value. More importantly, you are not mutating state directly. Instead, you are creating a new array by spreading the old array and adding a new value.

      Now that you have one action, you can create an action for incrementing a view.

      Create an action called incrementBird. Like the addBird action, this will take a bird as an argument and return an object with a type and a bird. The only difference is the type will be 'INCREMENT_BIRD':

      redux-tutorial/src/store/birds/birds.js

      const ADD_BIRD = 'ADD_BIRD';
      const INCREMENT_BIRD = 'INCREMENT_BIRD';
      
      export function addBird(bird) {
        return {
          type: ADD_BIRD,
          bird,
        }
      }
      
      export function incrementBird(bird) {
        return {
          type: INCREMENT_BIRD,
          bird
        }
      }
      
      const defaultBirds = [
        {
          name: 'robin',
          views: 1,
        }
      ];
      
      function birds(state=defaultBirds, action) {
        switch (action.type) {
          case ADD_BIRD:
            return [
              ...state,
              {
                name: action.bird,
                views: 1
              }
            ];
          default:
            return state;
        }
      }
      

      This action is separate, but you will use the same reducer. Remember, the actions convey the change you want to make on the data and the reducer applies those changes to return a new state.

      Incrementing a bird involves a bit more than adding a new bird. Inside of birds add a new case for INCREMENT_BIRD. Then pull the bird you need to increment out of the array using find() to compare each name with the action.bird:

      redux-tutorial/src/store/bird/birds.js

      const ADD_BIRD = 'ADD_BIRD';
      ...
      function birds(state=defaultBirds, action) {
        switch (action.type) {
          case ADD_BIRD:
            return [
              ...state,
              {
                name: action.bird,
                views: 1
              }
            ];
          case INCREMENT_BIRD:
            const bird = state.find(b => action.bird === b.name);
            return state;
          default:
            return state;
        }
      }
      

      You have the bird you need to change, but you need to return a new state containing all the unchanged birds as well as the bird you’re updating. Select all remaining birds with state.filter by selecting all birds with a name that does not equal action.name. Then return a new array by spreading the birds array and adding the bird at the end:

      redux-tutorial/src/store/bird/birds.js

      const ADD_BIRD = 'ADD_BIRD';
      ...
      
      function birds(state=defaultBirds, action) {
        switch (action.type) {
          case ADD_BIRD:
            return [
              ...state,
              {
                name: action.bird,
                views: 1
              }
            ];
          case INCREMENT_BIRD:
            const bird = state.find(b => action.bird === b.name);
            const birds = state.filter(b => action.bird !== b.name);
            return [
              ...birds,
              bird,
            ];
          default:
            return state;
        }
      }
      

      Finally, update the bird by creating a new object with an incremented view:

      redux-tutorial/src/store/bird/birds.js

      const ADD_BIRD = 'ADD_BIRD';
      ...
      function birds(state=defaultBirds, action) {
        switch (action.type) {
          case ADD_BIRD:
            return [
              ...state,
              {
                name: action.bird,
                views: 1
              }
            ];
          case INCREMENT_BIRD:
            const bird = state.find(b => action.bird === b.name);
            const birds = state.filter(b => action.bird !== b.name);
            return [
              ...birds,
              {
                ...bird,
                views: bird.views + 1
              }
            ];
          default:
            return state;
        }
      }
      

      Notice that you are not using the reducers to sort the data. Sorting could be considered a view concern since the view displays the information to a user. You could have one view that sorts by name and one view that sorts by view count, so it’s better to let individual components handle the sorting. Instead, keep reducers focused on updating the data, and the component focused on converting the data to a usable view for a user.

      This reducer is also imperfect since you could add birds with the same name. In a production app you would need to either validate before adding or give birds a unique id so that you could select the bird by id instead of name.

      Now you have two complete actions and a reducer. The final step is to export the reducer so that it can initialize the store. In the first step, you created the store by passing a function that returns an object. You will do the same thing in this case. The function will take the store and the action and then pass the specific slice of the store to the reducers along with the action. It would look something like this:

      export function birdApp(store={}, action) {
          return {
              birds: birds(store.birds, action)
          }
      }
      

      To simplify things, Redux has a helper function called combineReducers that combines the reducers for you.

      Inside of birds.js, import combineReducers from redux. Then call the function with birds and export the result:

      redux-tutorial/src/store/bird/birds.js

      import { combineReducers } from 'redux';
      const ADD_BIRD = 'ADD_BIRD';
      const INCREMENT_BIRD = 'INCREMENT_BIRD';
      
      export function addBird(bird) {
        return {
          type: ADD_BIRD,
          bird,
        }
      }
      
      export function incrementBird(bird) {
        return {
          type: INCREMENT_BIRD,
          bird
        }
      }
      
      const defaultBirds = [
        {
          name: 'robin',
          views: 1,
        }
      ];
      
      function birds(state=defaultBirds, action) {
        switch (action.type) {
          case ADD_BIRD:
            return [
              ...state,
              {
                name: action.bird,
                views: 1
              }
            ];
          case INCREMENT_BIRD:
            const bird = state.find(b => action.bird === b.name);
            const birds = state.filter(b => action.bird !== b.name);
            return [
              ...birds,
              {
                ...bird,
                views: bird.views + 1
              }
            ];
          default:
            return state;
        }
      }
      
      const birdApp = combineReducers({
        birds
      });
      
      export default birdApp;
      

      Save and close the file.

      Your actions and reducers are all set up. The final step is to initialize your store using the combined reducers instead of a placeholder function.

      Open src/index.js:

      Import the birdApp from birds.js. Then initialize the store using birdApp:

      redux-tutorial/src/index.js

      
      import React from 'react';
      import ReactDOM from 'react-dom';
      import './index.css';
      import App from './components/App/App';
      import * as serviceWorker from './serviceWorker';
      import { Provider } from 'react-redux'
      import { createStore } from 'redux'
      import birdApp from './store/birds/birds';
      
      const store = createStore(birdApp);
      
      ReactDOM.render(
        <React.StrictMode>
          <Provider store={store}>
            <App />
          </Provider>
        </React.StrictMode>,
        document.getElementById('root')
      );
      
      // If you want your app to work offline and load faster, you can change
      // unregister() to register() below. Note this comes with some pitfalls.
      // Learn more about service workers: https://bit.ly/CRA-PWA
      serviceWorker.unregister();
      

      Save and close the file. When you do the browser will refresh with your application:

      Bird watching app with form

      In this step you created actions and reducers. You learned how to create actions that return a type and how to build reducers that use the action to build and return a new state based on the action. Finally, you combined the reducers into a function that you used to initialize the store.

      Your Redux store is now all set up and ready for changes. In the next step you’ll dispatch actions from a component to update the data.

      Step 3 — Dispatching Changes in a Component

      In this step, you’ll import and call your actions from your component. You’ll use a method called dispatch to send the action and you’ll dispatch the actions inside of event handlers for the form and the button.

      By the end of this step, you’ll have a working application that combines a Redux store and your custom components. You’ll be able to update the Redux store in real time and will be able to display the information in your component as it changes.

      Now that you have working actions, you need to connect them to your events so that you can update the store. The method you will use is called dispatch and it sends a particular action to the Redux store. When Redux receives an action you have dispatched, it will pass the action to the reducers and they will update the data.

      Open App.js:

      • nano src/components/App/App.js

      Inside of App.js import the Hook useDispath from react-redux. Then call the function to create a new dispatch function:

      redux-tutorial/src/components/App/App.js

      import React from 'react';
      import { useDispatch, useSelector } from 'react-redux'
      import './App.css';
      
      function App() {
        ...
      }
      
      export default App;
      

      Next you’ll need to import your actions. Remember, actions are functions that return an object. The object is what you will ultimately pass into the dispatch function.

      Import incrementBird from the store. Then create an onClick event on the button. When the user clicks on the button, call incrementBird with bird.name and pass the result to dispatch. To make things more readable, call the incrementBird function inside of dispatch:

      redux-tutorial/src/components/App/App.js

      import React from 'react';
      import { useDispatch, useSelector } from 'react-redux'
      import { incrementBird } from '../../store/birds/birds';
      import './App.css';
      
      function App() {
        const birds = useSelector(state => state.birds);
        const dispatch = useDispatch();
      
        return (
          <div className="wrapper">
            <h1>Bird List</h1>
            <form>
              <label>
                <p>
                  Add Bird
                </p>
                <input type="text" />
              </label>
              <div>
                <button type="submit">Add</button>
              </div>
            </form>
            <ul>
              {birds.map(bird => (
                <li key={bird.name}>
                  <h3>{bird.name}</h3>
                  <div>
                    Views: {bird.views}
                    <button onClick={() => dispatch(incrementBird(bird.name))}><span role="img" aria-label="add">➕</span></button>
                  </div>
                </li>
              ))}
            </ul>
          </div>
        );
      }
      
      export default App;
      

      Save the file. When you do, you’ll be able to increment the robin count:

      Increment a bird

      Next, you need to dispatch the addBird action. This will take two steps: saving the input to an internal state and triggering the dispatch with onSubmit.

      Use the useState Hook to save the input value. Be sure to convert the input to a controlled component by setting the value on the input. Check out the tutorial How To Build Forms in React for a more in-depth look at controlled components.

      Make the following changes to your code:

      redux-tutorial/src/components/App/App.js

      import React, { useState } from 'react';
      import { useDispatch, useSelector } from 'react-redux'
      import { incrementBird } from '../../store/birds/birds';
      import './App.css';
      
      function App() {
        const [birdName, setBird] = useState('');
        const birds = useSelector(state => state.birds);
        const dispatch = useDispatch();
      
        return (
          <div className="wrapper">
            <h1>Bird List</h1>
            <form>
              <label>
                <p>
                  Add Bird
                </p>
                <input
                  type="text"
                  onChange={e => setBird(e.target.value)}
                  value={birdName}
                />
              </label>
              <div>
                <button type="submit">Add</button>
              </div>
            </form>
            <ul>
              ...
            </ul>
          </div>
        );
      }
      
      export default App;
      

      Next, import addBird from birds.js, then create a function called handleSubmit. Inside the handleSubmit function, prevent the page form submission with event.preventDefault, then dispatch the addBird action with the birdName as an argument. After dispatching the action, call setBird('') to clear the input. Finally, pass handleSubmit to the onSubmit event handler on the form:

      redux-tutorial/src/components/App/App.js

      import React, { useState } from 'react';
      import { useDispatch, useSelector } from 'react-redux'
      import { addBird, incrementBird } from '../../store/birds/birds';
      import './App.css';
      
      function App() {
        const [birdName, setBird] = useState('');
        const birds = useSelector(state => state.birds);
        const dispatch = useDispatch();
      
        const handleSubmit = event => {
          event.preventDefault();
          dispatch(addBird(birdName))
          setBird('');
        };
      
        return (
          <div className="wrapper">
            <h1>Bird List</h1>
            <form onSubmit={handleSubmit}>
              <label>
                <p>
                  Add Bird
                </p>
                <input
                  type="text"
                  onChange={e => setBird(e.target.value)}
                  value={birdName}
                />
              </label>
              <div>
                <button type="submit">Add</button>
              </div>
            </form>
            <ul>
              {birds.map(bird => (
                <li key={bird.name}>
                  <h3>{bird.name}</h3>
                  <div>
                    Views: {bird.views}
                    <button onClick={() => dispatch(incrementBird(bird.name))}><span role="img" aria-label="add">➕</span></button>
                  </div>
                </li>
              ))}
            </ul>
          </div>
        );
      }
      
      export default App;
      

      Save the file. When you do, the browser will reload and you’ll be able to add a bird:

      Save new bird

      You are now calling your actions and updating your birds list in the store. Notice that when your application refreshed you lost the previous information. The store is all contained in memory and so a page refresh will wipe the data.

      This list order will also change if you increment a bird higher in the list.

      Robin goes to the bottom on reorder

      As you saw in Step 2, your reducer is not concerned with sorting the data. To prevent an unexpected change in the components, you can sort the data in your component. Add a sort() function to the birds array. Remember that sorting will mutate the array and you never want to mutate the store. Be sure to create a new array by spreading the data before sorting:

      redux-tutorial/src/components/App/App.js

      import React, { useState } from 'react';
      import { useDispatch, useSelector } from 'react-redux'
      import { addBird, incrementBird } from '../../store/birds/birds';
      import './App.css';
      
      function App() {
        const [birdName, setBird] = useState('');
        const birds = [...useSelector(state => state.birds)].sort((a, b) => {
          return a.name.toLowerCase() > b.name.toLowerCase() ? 1 : -1;
        });
        const dispatch = useDispatch();
      
        const handleSubmit = event => {
          event.preventDefault();
          dispatch(addBird(birdName))
          setBird('');
        };
      
        return (
          <div className="wrapper">
            <h1>Bird List</h1>
            <form onSubmit={handleSubmit}>
              <label>
                <p>
                  Add Bird
                </p>
                <input
                  type="text"
                  onChange={e => setBird(e.target.value)}
                  value={birdName}
                />
              </label>
              <div>
                <button type="submit">Add</button>
              </div>
            </form>
            <ul>
              {birds.map(bird => (
                <li key={bird.name}>
                  <h3>{bird.name}</h3>
                  <div>
                    Views: {bird.views}
                    <button onClick={() => dispatch(incrementBird(bird.name))}><span role="img" aria-label="add">➕</span></button>
                  </div>
                </li>
              ))}
            </ul>
          </div>
        );
      }
      
      export default App;
      

      Save the file. When you do, the components will stay in alphabetical order as you increment birds.

      Cardinal stays on top

      It’s important to not try and do too much in your Redux store. Keep the reducers focused on maintaining up-to-date information then pull and manipulate the data for your users inside the component.

      Note: In this tutorial, notice that there is a fair amount of code for each action and reducer. Fortunately, there is an officially supported project called Redux Toolkit that can help you reduce the amount of boilerplate code. The Redux Toolkit provides an opinionated set of utilities to quickly create actions and reducers, and will also let you create and configure your store with less code.

      In this step, you dispatched your actions from a component. You learned how to call actions and how to send the result to a dispatch function, and you connected them to event handlers on your components to create a fully interactive store. Finally, you learned how to maintain a consistent user experience by sorting the data without directly mutating the store.

      Conclusion

      Redux is a popular single store. It can be advantageous when working with components that need a common source of information. However, it is not always the right choice in all projects. Smaller projects or projects with isolated components will be able to use built-in state management and context. But as your applications grow in complexity, you may find that central storage is critical to maintaining data integrity. In such cases, Redux is an excellent tool to create a single unified data store that you can use across your components with minimal effort.

      If you would like to read more React tutorials, check out our React Topic page, or return to the How To Code in React.js series page.



      Source link