jaystack / repatch

Dispatch reducers

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

dispatch won't trigger re-render?

leecade opened this issue · comments

// def actions
export const addTodo = name => state => async (dispatch, getState) => {
  const todos = getState().todos
  todos.push(name)
  await dispatch(state => ({...state, todos}))
}

// connect
import { connect } from 'react-redux'
import { addTodo } from './actions'

@connect(
  state => ({
    todos: state.todos
  }),
  {
    addTodo
  }
)
class App extends Component {
...

when call addTodo('name'), store.subscribe is triggered, but App component won't re-render, not sure anything missing or a bug?

The state.todos array needs to be assigned a new value in order for any subsequent render/component to pick up the change - its just how React works - so its not related to repatch. Try doing this:

export const addTodo = name => state => async (dispatch, getState) => {
  const todos = getState().todos
  dispatch(state => ({...state, todos: [...todos, name]}))
}

I close this issue by the previous comment.
React's rendering is very sensitive on immutable data. If you push your todo, the todos array reference won't change, and React can't take difference between the previous and the current state.

@leecade something else: you shouldn't use thunk to add todo synchronously. That's enough if you define a simple reducer:

const addToto = name => state => ({ ...state, todos: [...state.todos, name] })

Thunk middleware is useful for do some asynchronously, eg api calls.

@PeterAronZentai @jayhasyee thanks, it's really my negligence.