0% found this document useful (0 votes)
3 views2 pages

Redux Todoapp

int220

Uploaded by

1234ishankraj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

Redux Todoapp

int220

Uploaded by

1234ishankraj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

npm install @reduxjs/toolkit react-redux

store.js
import { configureStore } from "@reduxjs/toolkit";
import todoReducer from "./todoSlice";

const store = configureStore({


reducer: { todos: todoReducer },
});

export default store;

todoSlice.js
import { createSlice } from "@reduxjs/toolkit";

const todoSlice = createSlice({


name: "todos",
initialState: [],
reducers: {
addTodo: (state, action) => {
state.push(action.payload);
},
removeTodo: (state, action) => {
return state.filter((_, index) => index !== action.payload);
},
},
});

export const { addTodo, removeTodo } = todoSlice.actions;


export default todoSlice.reducer;

todoapp.js
import React, { useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { addTodo, removeTodo } from "./todoSlice";

const TodoApp = () => {


const [input, setInput] = useState("");
const todos = useSelector((state) => state.todos);
const dispatch = useDispatch();

const handleAdd = () => {


if (input.trim()) {
dispatch(addTodo(input));
setInput("");
}
};

const handleRemove = (index) => {


dispatch(removeTodo(index));
};

return (
<div>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Add a to-do"
/>
<button onClick={handleAdd}>Add</button>
<ul>
{todos.map((todo, index) => (
<li key={index}>
{todo} <button onClick={() => handleRemove(index)}>Remove</button>
</li>
))}
</ul>
</div>
);
};

export default TodoApp;

app.js

import React from "react";


import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import store from "./store";
import TodoApp from "./TodoApp";

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

You might also like