Setup

New Project

npx create-react-app my-app --template redux

Existing Project

yarn add react-redux @reduxjs/toolkit
yarn add -D redux-devtools

@reduxjs/toolkit => includes the Redux core with some sweet sugar, as well as other key packages like(Redux Thunk and Reselect)

1) Create Slice

redux/todos.js

import { createSlice } from '@reduxjs/toolkit'

const todosSlice = createSlice({
  name: 'todos',
  initialState: [],
  reducers: {
    //called on dispatch of type todos/addTodo
    addTodo(state, action) {
      const { id, text } = action.payload
      state.push({ id, text, completed: false })
    }, 
    toggleTodo(state, action) {
      const todo = state.find(todo => todo.id === action.payload)
      if (todo) {
        todo.completed = !todo.completed
      }
    }
  }
})

export const { addTodo, toggleTodo } = todosSlice.actions

export default todosSlice.reducer

//async dispatch
export const login = ({ username, password }) => async dispatch => {
  try {
    // const res = await api.post('/api/auth/login/', { username, password })
    dispatch(loginSuccess({username}));
  } catch (e) {
    return console.error(e.message);
  }
}

2) Create root reducer

redux/rootReducer.js

3) Add Store

index.js

4) Use in App

Last updated