I am new to React + Redux and I am building a todo app.
Property 'todos' is missing in type '{}' but required in type '{ todos: Todo[]; }'. TS2741
I think the problem is I fail to connect (react-redux) state to TodoList. I can confirm this because I jump from <TodoList /> to its function component connect(mapStateToProps)(TodoList) rather than, supposedly, connect(mapStateToProps)(TodoList)
CodeSandbox: https://codesandbox.io/s/flamboyant-dream-w7drj?file=/src/App.tsx:712-713
I have read the react-redux doc but I did not find how to fix this.
Code:
import React, { useState } from 'react';
import { connect } from 'react-redux'
import { addTodo} from './index'
function AddToDo() {
const [input, setInput] = useState('')
function handleInput(e: React.ChangeEvent<HTMLInputElement>) {
setInput(e.target.value)
}
//dispatch to store
function handleAddTodo() {
addTodo(input)
setInput('')
}
return (
<div>
<input type="text" onChange={(e) => handleInput(e)}/>
<button type="button" onClick={handleAddTodo}>
Add todo
</button>
</div>
)
}
//connect
connect(null, { addTodo })(AddToDo)
//TodoList
interface Todo {
id: number
text: string
}
interface TodoState {
todos: Todo[]
}
function TodoList({ todos}:{ todos: Todo[]}) {
return (
<ul className="todo-list">
{todos.map((todo: Todo, index) => {
return <Todo todo={todo} />;
})
}
</ul>
)
}
function mapStateToProps(state:TodoState) {
return {state}
}
connect(mapStateToProps)(TodoList)
//Todo
function Todo({ todo }: { todo: Todo }) {
return (
<li>
{todo}
</li>
)
}
function App() {
return (
<div className="App">
<AddToDo />
<TodoList /> <---------------------- Error info: Property 'todos' is missing in type '{}' but required in type '{ todos: Todo[]; }'. TS2741
</div>
);
}
export default App;
mapStateToPropsneeds to return an object. Instead ofreturn state.todos, change it toreturn {todos: state.todos};- Dom