DEV Community

AKSH DESAI
AKSH DESAI

Posted on

useReducer() Hook - Web dev Simplified

Part 1:-

App.js Code :-

import { useReducer } from "react";

const initialState = [
    {
        id: 1,
        label: 'aksh',
        Checked: false
    },
    {
        id: 2,
        label: 'rudra',
        Checked: false
    }
]

const reducer = (state) => {
    return [
        {
            id: 1,
            label: 'aksh1',
            Checked: true
        }
    ]

}

const App = () => {
    const [todos, dispatch] = useReducer(reducer, initialState)

    const handleOnChange = () => {
        dispatch();
    }
    return (
        <>
            <h1> Hello World </h1>

            {todos.map((todo) => {
                console.log(todo);
                return <label key={todo.id}>
                    <input type="checkbox" checked={todo.Checked} onChange={handleOnChange} />
                    {todo.label}
                </label>
            })}
        </>
    )
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Output :-

Output 1

Output 2


Part 2:-

App.js Code :-



import { useState, useReducer } from 'react'

const ACTIONS = {
    ADD_TODO: 'add-todo',
    TOGGLE_TODO: 'toggle-todo'
};

function reducer(todos, action) {
    switch (action.type) {
        case ACTIONS.ADD_TODO:
            if (todos === null) {
                return [newTodo(todos, action.payload.name)]
            }
            else {
                return [...todos, newTodo(todos, action.payload.name)]
            }
        case ACTIONS.TOGGLE_TODO:
            return todos.map((todo) => {
                if (todo.id === action.payload.id) {
                    return { ...todo, complete: !todo.complete };
                }
                else {
                    return todo;
                };
            })
        case 'blank':
            return null;
        default:
            return todos;
    }
};

function newTodo(prevTodos, name) {
    if (prevTodos === null) {
        localStorage.setItem('localtodos', JSON.stringify([{ id: Date.now(), name: name, complete: false }]));
    }
    else {
        localStorage.setItem('localtodos', JSON.stringify([...prevTodos, { id: Date.now(), name: name, complete: false }]));
    }
    return { id: Date.now(), name: name, complete: false }
}

const App = () => {
    const [name, setName] = useState("");
    const [todos, dispatch] = useReducer(reducer, JSON.parse(localStorage.getItem("localtodos"))
    );

    const handleSubmit = (e) => {
        e.preventDefault();
        dispatch({ type: ACTIONS.ADD_TODO, payload: { name: name } });
        setName("");
    };

    const handleChange = async (id) => {
        await dispatch({ type: ACTIONS.TOGGLE_TODO, payload: { id: id } })
        let newTodo = todos.map((todo) => {
            if (todo.id === id) {
                return { ...todo, complete: !todo.complete };
            }
            else {
                return todo;
            };
        })
        localStorage.setItem("localtodos", JSON.stringify(newTodo));
    };

    return (
        <>
            <form onSubmit={handleSubmit}>
                <input type="text" value={name} onChange={e => setName(e.target.value)} />
            </form>

            {todos === null ? '' : <input type="button" onClick={() => {
                localStorage.clear();
                dispatch({ type: 'blank' });
            }} value="cancel" />}

            {todos === null ? <h1> Add Some Notes to Preview </h1> : todos.map((todo) => {
                return <h3 style={{backgroundColor: todo.complete === false ? 'cyan' : ''}} key={todo.id} >
                    <input type="checkbox" checked={todo.complete} onChange={() => { handleChange(todo.id) }} />
                    {todo.name}
                    <br />
                </h3>
            })
            }
        </>
    )
};

export default App;
Enter fullscreen mode Exit fullscreen mode

*Output *

Output 3

Thank You.
You can follow us on:
Youtube
Instagram

Top comments (0)