Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

javascript - useEffect is dispatching an action infinitely even with dependencies

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


check the log here

question from:https://stackoverflow.com/questions/65837673/useeffect-is-dispatching-an-action-infinitely-even-with-dependencies

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The saga itself is creating an infinite loop because you use the same action name “GET_TODOS” for both initiating the fetch and storing the results of the fetch. The action that you put from fetchTodos will be picked up again by your takeEvery.

You want two separate action types, for example “REQUEST_TODOS” and “RECEIVE_TODOS”. The request action has no payload, while the success action has a payload with the array of todos from your fetch. Your reducer would ignore the request action (unless you want to use it to set a property like loading: true). For the success action, your reducer will store the results of your fetch from the payload property.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...