React State Management Using Easy Peasy

0
34
React State Management Using Easy Peasy


Quick Summary

According to the documentation,

Easy Peasy is an abstraction of Redux, providing a reimagined API that focuses on developer experience. It allows you to quickly and easily manage your state while leveraging strong architectural guarantees.

We’ll use Easy Peasy as the state manager of choice to build a note application that will help us learn how it works.

Introduction

In building React applications, one of the most important questions for developers includes managing the state effectively. In this tutorial, we will learn how to use Easy Peasy to manage state in React applications. We will understand the core concepts of Easy Peasy and some use cases for it, why it should be used for your next application, and we’ll build a simple example. Easy Peasy is open source with more than 4.1k stars on GitHub.

This tutorial will be beneficial to readers interested in learning how to manage state with Easy Peasy in their React applications or looking for alternatives to state management in a React application. This article requires a basic understanding of React and JavaScript.

What is Easy Peasy?

Easy Peasy is a state manager that works similar to Redux but with less code and complexity than Redux. Easy Peasy was built to provide the same performance as Redux and other state managers.

Core concepts of Easy Peasy include the following hooks and methods.

  • Store: Similar to Redux, Easy Peasy requires a store powered by React Context, which will disclose the application state to certain parts of your application.
  • State: This is an essential part of Easy Peasy because it uses the state or model to define your application store.
  • Thunk Action: This is used in Easy Peasy to perform operations that are termed side effects, such as making an API call.
  • Action: Actions used to update the application store.
  • UseStoreState: This is a custom hook from Easy Peasy that gives our components access to the application’s store state.
  • UseStoreActions: As the name implies, this hook gives our components access to the store’s actions.
  • Provider: Similar to Redux, Easy Peasy comes with a Provider method that exposes the store to our React app. This is done so our components will be able to consume the store with React hooks.

Easy Peasy can be installed using the command below. (We prefer using yarn to using npm.)

1yarn add easy-peasy

Why Easy Peasy?

Easy Peasy’s main objective is to improve state management for React developers and make for an easier way of managing application states with less code and boilerplate. Easy Peasy removes the abstractions of Redux and simplifies state management with a simpler process, making it easier for anyone to use in React applications.

Easy Peasy also supports React-Hooks-based APIs and Redux middleware such as Redux thunks out of the box. Easy Peasy can be set up to perform API requests as a side effect using thunk actions. Please see the API call below for an example of a request to delete a user and get a user by their id.

1import {

2 action,

3 computed,

4 createContextStore,

5 thunk,

6} from "easy-peasy";

7import { deleteUser, getUserById } from "./user";

8

9const UserStore = createContextStore({

10 getUsers: thunk(async (actions) => {

11 actions.setIsLoading();

12 try {

13 const { data } = await getUsers();

14 actions.setUsers(data);

15 } catch (e) {

16 actions.setError(e);

17 }

18 actions.setIsLoading();

19 }),

20 getUserById: thunk(async (actions, id) => {

21 actions.setIsLoading();

22 try {

23 const { data } = await getUserById(id);

24 actions.setUser(data);

25 } catch (e) {

26 actions.setError(e);

27 }

28 actions.setIsLoading();

29 }),

30});

In the code block, we get users from the API using the getUser thunk and setting the user as our current state. We also did the same thing with the deleteUser method.

Easy Peasy vs. Redux/MobX/HookState

Like other state managers like Redux and MobX, Easy Peasy uses a single store to handle the application state, and it also uses actions as a source of data for the application store. It’s important to note that Easy Peasy uses Redux internally to manage state.

Unlike Redux and MobX, Easy Peasy requires little to no boilerplate code to work with. Easy Peasy uses Immer under the hood, which gives developers the power to interact with data while keeping the benefits of the immutable data.

Easy Peasy allows developers to extend the application store using Redux middleware and other custom hooks to enhance performance.

Compared to React HookState, Easy Peasy offers more ease of managing and updating state with a single store and sharing information with components using custom hooks such as useStoreState and useStoreAction, which comes out of the box with Easy Peasy.

With its ease and zero boilerplate code, Easy Peasy can be used to manage state from simple React to-do applications to larger applications. Easy Peasy also provides support for TypeScript out of the box.

Building Notes application with Easy Peasy

Now that we know the core concepts of Easy Peasy, we’ll be building a notes application and managing the state with Easy Peasy. The app will allow users to add, delete and temporarily cancel a note using a toggle.

Without further ado, let’s start!

Setting Up Your Environment

First, let’s create a bare React application. Write the code block below on your terminal.

1create-react-app easy-peasy-notes-app

The above code will create a bare React application using the create-react-app package. Move into the project directory and add the dependencies that we will need for our application.

1cd easy-peasy-notes-app

2yarn add easy-peasy uuid

In the above code block, we installed:

  • Easy-peasy: our state manager for our application
  • uuid: This is to create a unique string of notes for our application

Start the project server using the command below if you’ve done this.

Next, let’s create a components folder in our src directory. We will be creating three components and an app store for our application.

Creating an App Store

As mentioned above, Easy Peasy works with a store to hold the application state. With this, we can access the application store and update the state. We will need to set up a function to add, toggle, and delete notes in our application in the store. To create our app store, first create a Store.js file in our project’s src directory, next let’s add logic to our store.

1import { action } from "easy-peasy";

2import uuid from "uuid";

3

4export default {

5 notes: [],

6 setNote: action((state, notes) => {

7 state.notes = notes;

8 }),

9 addNote: action((state, note) => {

10 note.id = uuid.v4();

11 state.notes.push(note);

12 }),

13 toggleNote: action((state, id) => {

14 state.notes.map((note) => {

15 return note.id === id

16 ? (note.completed = !note.completed)

17 : note;

18 });

19 }),

20 removeNote: action((state, id) => {

21 state.notes = state.notes.filter(

22 (note) => note.id !== id

23 );

24 }),

25};

We imported actions from easy-peasy in the code above. The actions will be used to update our application store. We imported uuid to give unique ids to our notes when they are created. We initialized notes as an empty array object and created a function setNote that takes in the state and note parameters and sets the current note as the value for state.notes. The addNote function takes in two parameters: an initial state and a note. We assign the note id to one automatically provided by uuid.v4() and push the new note into the state.notes array. The toggleNote parameter takes in the state and id parameters and uses the native JavaScript map object to cross off the completed notes by toggling the value of note.completed, the removeNote object deletes a note using the filter object.

In the next section, we will use the logic above to create our application’s component.

Building the Note component

Here, we will build our note component, the primary component for how each list will look on our application. Let’s create a components folder in our project’s src directory and create a new file, Note.jsx. Inside it, write the code block below.

1import React from "react";

2import { useStoreActions } from "easy-peasy";

3

4const Note = ({ note }) => {

5 const { completed } = note;

6 const removeNote = useStoreActions(

7 (actions) => actions.removeNote

8 );

9 const toggleNote = useStoreActions(

10 (actions) => actions.toggleNote

11 );

12 return (

13 <li className="d-flex justify-content-between align-items-center mb-2">

14 <span

15 className="h2 mr-2"

16 style={{

17 textDecoration: completed ? "line-through" : "",

18 cursor: "pointer",

19 }}

20 onClick={() => toggleNote(note.id)}

21 >

22 {note.title}

23 </span>

24 <button

25 onClick={() => removeNote(note.id)}

26 className="btn btn-danger btn-lg"

27 >

28 &times;

29 </button>

30 </li>

31 );

32};

33

34export default Note;

Here, the useStoreActions hook from easy-peasy gives our Note component access to the actions in the store: in this case, toggleNote to cross off a note as completed and addNote to add a new note. We returned the li tag, which contains the new notes.

Next, we add a delete button for our application. Similar to toggling a note, we add an onClick event that takes in the removeNote action. If we did this correctly, our app should look like the image below.

Notes component

Building Notes component

This component will act as a render for our notes. Here we will add a header component for our application name and render all our notes in this component, let’s do that below.

1import React from "react";

2import { useStoreState } from "easy-peasy";

3import Note from "./Note";

4const Notes = () => {

5 const notes = useStoreState((state) => state.notes);

6 return (

7 <>

8 <h1 className="display-4">Notes</h1>

9 {notes.length === 0 ? (

10 <h2 className="display-3 text-capitalize">

11 Please add note

12 </h2>

13 ) : (

14 notes.map((note) => (

15 <Note key={note.id} note={note} />

16 ))

17 )}

18 </>

19 );

20};

21

22export default Notes;

Here, we import the [useStoreState](https://easy-peasy.now.sh/docs/api/use-store-state.html) hook from easy-peasy. The useStoreState grants our component access to the store’s state. Next, we create a functional component, notes, and using the useStorestate, we assign notes to the state of the application found on the store. As an edge case using a ternary operator, we will drop a text for the user to add a note if they haven’t and render a note if they did. You can learn more about ternary operators here.

Building NotesForm Component

This component will be the bulk of our application. Here we will handle submitting our notes and setting them as the updated value of our application state. Let’s build the component below.

1import React, { useState } from "react";

2import { useStoreActions } from "easy-peasy";

3

4const NotesForm = () => {

5 const [title, setTitle] = useState("");

6 const [err, setErr] = useState(false);

7 const addNote = useStoreActions(

8 (actions) => actions.addNote

9 );

10 const handleSubmit = (e) => {

11 e.preventDefault();

12 if (title.trim() === "") {

13 setErr(true);

14 } else {

15 setErr(false);

16 addNote({

17 title,

18 completed: false,

19 });

20 }

21 setTitle("");

22 };

23 return (

24 <>

25 <form

26 onSubmit={handleSubmit}

27 className="d-flex py-5 form-inline"

28 >

29 <input

30 type="text"

31 placeholder="Add Todo Title"

32 value={title}

33 className="form-control mr-sm-2 form-control-lg"

34 onChange={(e) => setTitle(e.target.value)}

35 />

36 <button

37 type="submit"

38 className="btn btn-success btn-lg rounded"

39 >

40 Add Note

41 </button>

42 </form>

43 {err && (

44 <div className="alert alert-dismissible alert-danger">

45 <button

46 type="button"

47 className="close"

48 data-dismiss="alert"

49 onClick={() => setErr(false)}

50 >

51 &times;

52 </button>

53 <strong>Oh oh!</strong>{" "}

54 <span className="alert-link">

55 please add a valid text

56 </span>

57 </div>

58 )}

59 </>

60 );

61};

62

63export default NotesForm;

In this component, to access our project’s action objects in the store, we imported the useStoreActions and initialized the addNote action for adding a note in our component. Next, we created an input form that includes input for adding notes, submitting a note to be added, and a button for alert for when a user tries to add an empty note using the input.

The final act will be to set up our App.js file and wrap up our application using a Provider and restart our server to see our final application. Let’s do that in the code block below.

1import React from "react";

2import "./styles.css";

3import Notes from "./components/Notes";

4import NotesForm from "./components/NotesForm";

5

6import { StoreProvider, createStore } from "easy-peasy";

7import store from "./Store";

8

9const Store = createStore(store);

10function App() {

11 return (

12 <StoreProvider store={Store}>

13 <div className="container">

14 <NotesForm />

15 <Notes />

16 </div>

17 </StoreProvider>

18 );

19}

Here, we import the StoreProvider and createStore. The StoreProvider exposes the store to our application so that our components can consume the store using hooks. The createStore, similar to Redux, creates a global store based on the models we’ve provided. Next, we wrapped our App component using the store as a parameter of the StoreProvider.

Once done correctly, our app should look like the image below.

Easy Peasy note application

Open Source Session Replay

OpenReplay is an open-source alternative to FullStory and LogRocket. It gives you full observability by replaying everything your users do on your app and showing how your stack behaves for every issue. OpenReplay is self-hosted for full control over your data.

replayer.png

Happy debugging for modern frontend teams – start monitoring your web app for free.

API Request with Easy Peasy

In this section, we will look at handling API requests with Easy Peasy. To better understand this, we will be building a currency converter using React, TypeScript, and Easy Peasy to manage state. In our application, users should be able to convert dollars to any currency. Users can input the amount they’d like to convert and the currency they’re converting to.

First, we will create a react app using the command below. We will add typescript support and reactstrap for styling.

1create-react-app currency-converter

2yarn add @testing-library/jest-dom @testing-library/react @testing-library/user-event @types/jest @types/node @types/react @types/react-dom axios bootstrap easy-peasy reactstrap typescript

For TypeScript support, create a tsconfig.json file in the root directory of our project and copy the code block below into it.

1{

2 compilerOptions: {

3 target: "es5",

4 lib: ["dom", "dom.iterable", "esnext"],

5 allowJs: true,

6 skipLibCheck: true,

7 esModuleInterop: true,

8 allowSyntheticDefaultImports: true,

9 strict: true,

10 forceConsistentCasingInFileNames: true,

11 noFallthroughCasesInSwitch: true,

12 module: "esnext",

13 moduleResolution: "node",

14 resolveJsonModule: true,

15 isolatedModules: true,

16 noEmit: true,

17 jsx: "react-jsx",

18 },

19 include: ["src"],

20};

After we’ve added the code above, to finish TypeScript configuration for our project, create a new file in the root directory of our project named react-app-env.d.ts. This file will reference the type of react-scripts in our project. You can learn more about it here.

1/// <reference types="react-scripts" />

Building Our App’s Store

To get started on our project properly, in the src directory of your project, create a store folder for our app’s store and inside it, create two files, index.ts and typehook.ts. Our index.ts file will contain our TypeScript interfaces for our API functions. Our application will store actions while our typehook.ts will contain Typed hooks from Easy Peasy. We will create interfaces for our API requests in the code block below.

1import {

2 createStore,

3 Action,

4 action,

5 Thunk,

6 thunk,

7} from "easy-peasy";

8import axios from "../axios";

9

10export interface ICurrency {

11 currency_name: string;

12 currency_code: string;

13 decimal_units: string;

14 countries: string[];

15}

16interface IAllCurrencies {

17 data: ICurrency[];

18 updateResult: Action<IAllCurrencies, ICurrency[]>;

19 getAllCurrencies: Thunk<IAllCurrencies>;

20}

21interface ICurrencyRates {

22 rates: { [key: string]: string };

23 updateRates: Action<ICurrencyRates, any>;

24 getCurrencyRates: Thunk<ICurrencyRates>;

25}

26interface IConversion {

27 data: {

28 to: string,

29 amount: string,

30 };

31 updateTo: Action<IConversion, string>;

32 updateAmount: Action<IConversion, string>;

33}

34export interface IStore {

35 allCurrencies: IAllCurrencies;

36 currencyRates: ICurrencyRates;

37 conversion: IConversion;

38}

39

40const store =

41 createStore <

42 IStore >

43 {

44 allCurrencies: {

45 data: [],

46 updateResult: action((state, payload) => {

47 state.data = Object.values(payload);

48 }),

49 getAllCurrencies: thunk(async (actions) => {

50 try {

51 const res = await axios.get(`/currencies`);

52 actions.updateResult(res?.data?.response?.fiats);

53 } catch (error) {

54 console.log(error);

55 }

56 }),

57 },

58 currencyRates: {

59 rates: {},

60 updateRates: action((state, payload) => {

61 state.rates = payload;

62 }),

63 getCurrencyRates: thunk(async (actions) => {

64 try {

65 const res = await axios.get(`/latest`);

66 actions.updateRates(res?.data?.response?.rates);

67 } catch (error) {

68 console.log(error);

69 }

70 }),

71 },

72 conversion: {

73 data: {

74 to: "",

75 amount: "",

76 },

77 updateTo: action((state, payload) => {

78 state.data.to = payload;

79 }),

80 updateAmount: action((state, payload) => {

81 state.data.amount = payload;

82 }),

83 },

84 };

85

86export default store;

Here, we created interfaces that define the contract on our properties. For example, in ICurrency we enforced the name, code, decimal units, and countries to be of type string. In IAllCurrencies, we define the data we’ll get from the API as an array containing the object we’ve defined in ICurrency. We also enforce our updateResult work based on the interface of IAllCurrencies and accept a payload of ICurrency in an array. The getAllCurrencies method uses a Thunk to perform asynchronous functions. We have added an interface for ICurrencyRates. We defined rates to take in objects with keys that must be strings and accept a string payload. updateRates will work with the data and any data type. getCurrencyRates uses Thunk to perform asynchronous functions with the data returned.

To create a store, we first called the easy-peasy store. In our case, we structured the store to use the IStore interface. Next, we called the allCurrencies object from the IStore. In it, we will receive the data as an array. Like Redux, to update a state in easy peasy, you’d use an action. We defined the action updateResult, which acts as a reducer. It takes in our current state and the user’s payload, and sets the current state using the values we get from the user’s payload. You can learn more about updating the store and createStore.

To getAllCurrencies, we performed an async operation using axios to get all currencies and use actions from setting the data as a response. We wrapped the full application with a try…catch method in case of errors. We performed similar functions in our currencyRate object, updating the state with an action, performing an async operation to get the latest rates from the API, and setting the state using the data we receive.

The Conversion object converts the amount inputted by the user from dollars to any currency the user chooses. We defined an action that updates and renders the amount converted to the user to display the amount.

Building our Store Type Hooks

When using Easy Peasy with TypeScript, hooks are often recommended to have types. This is usually done with interfaces defined in the project store. In this section, we will add types to the hooks we will be using in our application. To do this, inside our store directory, create a new file called typehook.ts. Inside it, write the code block below.

1import { createTypedHooks } from "easy-peasy";

2import { IStore } from "./index";

3

4const typedHooks = createTypedHooks<IStore>();

5

6export const useStoreActions = typedHooks.useStoreActions;

7export const useStoreDispatch = typedHooks.useStoreDispatch;

8export const useStoreState = typedHooks.useStoreState;

In the code block above, we are adding types to our useStoreActions, useStoreDispatch, and our useStoreState hooks. With this, we are configuring it to the interfaces we’ve defined in our IStore. By doing this, whatever actions we are dispatching here will come from actions from the store.

In this section, we will add a Header to our application. The application header will contain our header, input fields for the user to add the amount, and the currency they wish to convert. First, we’ll create a components folder in our’ src’ directory. Inside that folder, we’ll create a header folder, which will contain a header.tsx file. Let’s add the logic for this.

1import { useState } from "react";

2import {

3 Button,

4 Form,

5 FormGroup,

6 Input,

7 Jumbotron,

8} from "reactstrap";

9import { ICurrency } from "../../store";

10import {

11 useStoreState,

12 useStoreActions,

13} from "../../store/typehook";

14

15const Header = () => {

16 const allCurrencies = useStoreState(

17 (state) => state.allCurrencies.data

18 );

19 const setAmountToConvert = useStoreActions(

20 (actions) => actions.conversion.updateAmount

21 );

22 const setCurrencyToConvertTo = useStoreActions(

23 (actions) => actions.conversion.updateTo

24 );

25 const [to, setTo] = useState<string>("");

26 const [amount, setAmount] = useState<string>("");

27

28 const onSubmitHandler = (e: {

29 preventDefault: () => void;

30 }) => {

31 e.preventDefault();

32 to && amount && setAmountToConvert(amount);

33 to && amount && setCurrencyToConvertTo(to);

34 };

35};

We imported the ICurrency object from our store in the code block above. We also imported useStoreState and useStoreActions from our custom typed hooks.

We initialized our Header as a functional component. Next, we create a constant allCurrencies to get the state of allCurrencies in our store. With setAmountToConvertTo, we called an action. The action we called is the updateAmount action from the store.

Using React useState, we defined the state we wanted to update. We added a <string> to let our app know that the state we are updating and defining is of string type.

We created a function onSubmitHandler to handle submissions, which converts the amount and currency the user input on the submission.

To finish our Header component, let’s render the input fields using react strap for our components and bootstrap for styling. We will append the code block below to the functions defined at the beginning of this section.

1return (

2 <div className="text-center">

3 <Jumbotron fluid>

4 <h1 className="display-4">Currency Converter</h1>

5 <div className="w-50 mx-auto">

6 <Form id="my-form" onSubmit={onSubmitHandler}>

7 <FormGroup className="d-flex flex-row mt-5 mb-5">

8 <Input

9 type="number"

10 value={amount}

11 onChange={(e) => setAmount(e.target.value)}

12 placeholder="Amount in Number"

13 />

14 <Input

15 type="text"

16 value="from USD ($)"

17 className="text-center w-50 mx-4"

18 disabled

19 />

20 <Input

21 type="select"

22 value={to}

23 onChange={(e) => setTo(e.target.value)}

24 >

25 <option>Converting to?</option>

26 {allCurrencies.map((currency: ICurrency) => (

27 <option

28 key={currency?.currency_code}

29 value={currency?.currency_code}

30 >

31 {currency?.currency_name}

32 </option>

33 ))}

34 </Input>

35 </FormGroup>

36 </Form>

37 <Button

38 color="primary"

39 size="lg"

40 block

41 className="px-4"

42 type="submit"

43 form="my-form"

44 >

45 Convert

46 </Button>

47 </div>

48 </Jumbotron>

49 </div>

50);

Here, we built the input fields for our application, one for the amount to be converted and the currency. If done correctly, our app should look similar to the image below.

Header component

Adding Currency API

To get the latest conversion rates and countries, We will be using the rapid API currency API. First, create a new folder axios in our src directory. Create a new file, index.tsx inside this folder.

Next is to visit Rapid API and sign up to get an APIKey when we do this, paste your API base URL and API keys inside our index.tsx in the format below

1import axios from "axios";

2export default axios.create({

3 baseURL: "https://currencyscoop.p.rapidapi.com",

4 headers: {

5 "x-rapidapi-key": "your api key goes here",

6 "x-rapidapi-host": "currencyscoop.p.rapidapi.com",

7 },

8});

Let’s configure our App.tsx in the next section to complete our application.

Configuring App.tsx

First, We will import all our actions and states from typedhooks and initialize them in our App.tsx. Let’s do that below.

1import { useEffect } from "react";

2import {

3 useStoreActions,

4 useStoreState,

5} from "./store/typehook";

6import Header from "./components/header/Header";

7

8const App = () => {

9 const getAllCurrencies = useStoreActions(

10 (actions) => actions.allCurrencies.getAllCurrencies

11 );

12 const getCurrencyRates = useStoreActions(

13 (actions) => actions.currencyRates.getCurrencyRates

14 );

15 const currencyRates = useStoreState(

16 (state) => state.currencyRates.rates

17 );

18 const amountToConvert = useStoreState(

19 (state) => state.conversion.data.amount

20 );

21 const currencyConvertingTo = useStoreState(

22 (state) => state.conversion.data.to

23 );

24

25 useEffect(() => {

26 getAllCurrencies();

27 getCurrencyRates();

28 }, [getAllCurrencies, getCurrencyRates]);

29

30 const equivalence = () => {

31 const val = Number(currencyRates[currencyConvertingTo]);

32 return val * parseInt(amountToConvert);

33 };

34

35 return (

36 <div

37 style={{ background: "#E9ECEF", height: "100vh" }}

38 className="container-fluid"

39 >

40 <Header />

41 <div className="w-50 mx-auto">

42 {amountToConvert && currencyConvertingTo ? (

43 <h2>Result:</h2>

44 ) : null}

45 {amountToConvert ? (

46 <h3>

47 ${amountToConvert} = {equivalence()}

48 </h3>

49 ) : null}

50 </div>

51 </div>

52 );

53};

54

55export default App;

Similar to what we did in our typedhooks file, in the code block above, we initialized all our store functions such as the getAllCurrencies and getCurrencyRates in this component. We used React useEffect hook to call the actions getAllCurrencies and getCurrencyRates from our store.

Next, we initialized a function equivalence that converts the currency rates from an object and returns the value we get from the API, and multiplies it by the amount inputted by the user as an integer.

To conclude, we used bootstrap and react strap to build components for our input. If done correctly, our app should look like this.

easy peasy currency converter

Conclusion

In this article, we learned about Easy Peasy, a state manager for React applications focused on providing a better experience for developers. We also went through the process of creating a notes application using Easy Peasy to manage the state. We also detailed the pros of using easy-peasy to manage state for your next application. Have fun using Easy Peasy for your next React application!

Resources

The notes app can be found on Codesandbox, and the currency converter is here.



Source link

Leave a reply

Please enter your comment!
Please enter your name here