DEV Community

AKSH DESAI
AKSH DESAI

Posted on

1

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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more