I'm having an infinite dispatch when using dispatch within useEffect
.
import React, { useEffect } from "react"
import TodoItem from "./TodoItem"
import { useDispatch, useSelector } from "react-redux"
import { getTodos } from "../redux/actions"
const TodoList = () => {
const dispatch = useDispatch()
useEffect(() => {
dispatch(getTodos())
}, [getTodos])
const todos = useSelector(state => state)
return (
<div style={{ width: "75%", margin: "auto" }}>
<h3>Todo List</h3>
{console.log("mounted")}
{todos &&
todos.map(todo => {
return <TodoItem key={todo.id} title={todo.title} id={todo.id} />
})}
{todos && !todos.length && <h3>There are no tasks to do. Add one!</h3>}
</div>
)
}
export default TodoList
sagas.js:
import { call, put, takeEvery } from "redux-saga/effects"
const apiUrl = "https://jsonplaceholder.cypress.io/todos"
function getApi() {
return fetch(apiUrl, {
method: "GET",
headers: {
"Content-Type": "application/json"
}
})
.then(response => response.json())
.catch(error => {
throw error
})
}
function* fetchTodos(action) {
try {
const todos = yield call(getApi)
const todosList = todos.slice(0, 20)
yield put({ type: "GET_TODOS", todosList })
} catch (error) {
console.log({ error })
}
}
function* todoSagas() {
yield takeEvery("GET_TODOS", fetchTodos)
}
export default todoSagas
question from:
https://stackoverflow.com/questions/65837673/useeffect-is-dispatching-an-action-infinitely-even-with-dependencies 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…