samedi 20 février 2021

Redux: Cannot read property 'getState' of undefined

currently I am learning Redux to create a simple todo app with React. This is how I have done

this is my reducer and store:

/redux/todo.js

const initialState = {
  items: []
};

const ADD_TODO = "ADD_TODO";

export const addTodo = (text) => ({
  type: ADD_TODO,
  payload: text
});

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case "ADD_TODO":
      return {
        ...state,
        items: [...state.items, action.payload]
      };
    default:
      return state;
  }
};

export default reducer;

/redux/store.js

import { createStore, combineReducers } from "redux";

import todoReducer from "./todo";

const reducer = combineReducers({
  todo: todoReducer
});

export default createStore(reducer);

this is my component to map with redux:

/components/TodoApp.js

import React, { useState } from "react";

export default function TodoApp({ todos, addTodo }) {
  const [text, setText] = useState("");

  return (
    <div>
      <input
        type="text"
        value={text}
        onChange={(e) => setText(e.target.value)}
      />
      <button
        onClick={() => {
          addTodo(text);
        }}
      >
        Add
      </button>
      <ul>
        {todos.map((todo) => (
          <li>{todo}</li>
        ))}
      </ul>
    </div>
  );
}

This is how I bind the store with the UI:

/bindings/TodoApp.js

import { connect } from "react-redux";
import TodoApp from "../components/TodoApp";
import { addTodo } from "../redux/todo";

const mapStateProps = (state) => {
  return {
    todos: state.todo.items
  };
};

const mapActionsToProps = {
  addTodo
};

export default connect(mapStateProps, mapActionsToProps)(TodoApp);

Then I import it in the root component:

App.js

import "./styles.css";
import TodoApp from "./bindings/TodoApp";

export default function App() {
  return (
    <div className="App">
      <TodoApp />
    </div>
  );
}

`

And finally, I add of Redux to index file:

index.js

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

const rootElement = document.getElementById("root");
ReactDOM.render(
  <Provider store={store}>
    <StrictMode>
      <App />
    </StrictMode>
  </Provider>,
  rootElement
);

And this is the error I got:

enter image description here

Please help me to deal with it, thank you so much, if it is possible, please modify the code in this codesandbox link here

Once again, thank you so much and have a good day




Aucun commentaire:

Enregistrer un commentaire