DEV Community

Discussion on: Why I Stopped Using Redux

Collapse
 
marianban profile image
Marian Ban

The redux toolkit version is less boiler-platy:

const todosSlice = createSlice({
  name: 'todos',
  initialState: [],
  reducers: {
    setTodos: (_, todos) => todos,    
  }
})

const { setTodos } = todosSlice.actions;

export const fetchTodos = () => async (dispatch) => {
  const { data } = await axios.get("/api/todos");
  dispatch(setTodos(data));
}

export const App = () => {
  const todos = useSelector((state) => state.todos);
  const dispatch = useDispatch();

  useEffect(() => {   
    dispatch(fetchTodos());
  }, []);

  return (
    <ul>{todos.length > 0 && todos.map((todo) => <li>{todo.text}</li>)}</ul>
  );
};