Redux in Simple Todo App

Beginnar guide to react-redux

react

06-April-2020

So you come pass by this post, then you’re interested in react, this is going to be a simple app just for explain redux. You’re already knew redux maybe you can skip it, but don’t forget there is always best practice for every code so maybe my way will make it more clear, so stay for while 🧐. So what is redux ? in simple words definition of redux is:

“Redux is a predictable state container for JavaScript applications”

We will care a lot about file structure of our app in this article, so read carefully and follow along.👨🏻‍💻

First thing first that we already installed create-react-app. than you can do like this

create-react-app simple-todo-app

open it via your editor and for me is VSCODE. take a look into file structure.It should be like this: react-redux

Now we will eject this app

Disclaimer: You don’t have to do this, just in my case I would like always use it with “eject”

yarn eject

so what eject does, actually create-react-app encapsulate the app from manipulating file structure and with eject you can do, and also installing another modules that might not working without eject command. your file structure won’t be change just with new folder scripts but now you will be able to change them you will be asked: ? Are you sure you want to eject? This action is permanent. (y/N)

answer: Y and here we go

now let’s install redux, react-redux, you might be using redux-logger, redux-thunk and that’s will be covered with another tutorials 🤩

yarn install -D redux react-redux

now change your files structure to be like this, and make sure that import statements are correct from its corresponding files.

Code-structure

In App.js we will create form with one input field and button where we can add or remove todo

App-redux-simple-todo-app

now we will create our redux reducer, in reducers folder create TodoReducer.js, and write reducer function in it like:

const INITIAL_STATE = ["read book", 'play basketball']

export const reducer = (state =INITIAL_STATE, action) => {
	// depending to the action type will reducer act or manipulate the state
	switch(action.type) {
		case 'ADD_TODO': 
			state = [..state, action.todo]
			break;
		case 'DELETE_TODO':
			state = [...state.filter((todo, index)=> index !== action.todoIndex)]
			break
		default: return state	
	}
	return state;
}

then we will create our actions which just functions that return type of action to the reducer. In Actions folder create a file named: TodoActions.js

export const addTodo = (todo) => ({
	type: 'ADD_TODO',
	todo
})

export const deleteTodo = (todoIndex) => ({
	type: "DELETE_TODO",
	todoIndex
})

Time to create our store and link it with our app. in index.js do the following …

import React from 'react'
import ReactDOM from 'react-dom'

import './assets/index.css'

import App from './containers/App'

import Provider from 'react-redux'

import { createStore, combineReducers } from 'redux'

import { reducer as todoReducer } from './reducers/TodoReducer'

const store = createStore(combineReducers({ todos: todoReducer }))


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

now everything is ready to connect our app with redux store. in App.js we will use connect function provided from ‘react-redux’ and wrap App in export place with it. check it below..

import { connect } from 'react-redux';
import { addTodo, deleteTodo } from '../actions/TodoActions';

....

const mapStateToProps = state => ({
	todoList: state.todos
})

const mapDispatchToProps = dispatch => ({
	addTodo: (newTodo) => dispatch(addTodo(newTodo)),
	deleteTodo: (todoIndex) => dispatch(deleteTodo(todoIndex))
})

export default connect(mapStateToProps, mapDispatchToProps)(App)

now to explain it connect function takes two parameters, which are mapStateToProps => where I can get my state mapDispatchToProps => where i can use actions now my actions and state:todos are already in props so I could use them, and refactor my code to use actions from ‘state’ not the local After refactoring app.js, it should like this: 1*IL3Nlzz-ttaLzwQDEcUMSw Voilà, now we have our app connect to redux and can use it to any components that you want.

1*lSRgYh2weWs7VevEGUT1uQ

In recap we just have created todo app with redux, the idea is just to make it clear as much as possible, there are a lot of things that you can do to make better code like separate your store in file and installing logger to show actions in console which is always better than you can follow actions with nice view etc.. Thank you to read my article, I hope that it was clear as intended to be. follow me to get more in redux, in the next articles I’m going through redux to handle synchronous request, and also redux-saga.

See you next time, Happy Coding ⚛


Links:

YouTube


Published on CodeReview by Mustafa Alroomi on 06-April-2020