Search code examples
reduxdispatch

redux dispatch does not work


I am a redux beginner, everything is confusing for me right now. I am trying to create a store and dispatch a new value to the store, but it does not work, can someone help? thanks

import {createStore, combineReducers} from 'redux';
import uuid from 'uuid';

const state={
    id:0,
    numbers:[]
}

const randomNumber=()=>{...}

//reducer

const reducer=(state={},action)=>{
    switch(action.type){
        case 'ADD_NUMBER':
        const newNumber={id:state.id+1, number:randomNumber()}
        return {
            ...state,
            id:uuid(),
            numbers:[...state.numbers,newNumber]
        }
    }
}

//store
const store=createStore(reducer)
store.subscribe(()=>{const state=store.getState})
console.log('new state should update, but it does not: ', state)

const addNumber =()=>({type: 'ADD_NUMBER'})

//dispatch
store.dispatch(addNumber())

this is my error enter image description here


Solution

  • Issue is in this line,

    const reducer = (state = {}, action) => {
    

    Note that you have initialized your state to an empty object {}. So when you try to spread the state.numbers you are getting this error because numbers is not defined in the initial state.

    return {
       ...state,
       id:uuid(),
       numbers:[...state.numbers,newNumber]
    }
    

    A minimal example that reproduces your issue,

    const bad = (state = {}) => {
      return {
        numbers:[...state.numbers]
      }
    }
    
    bad();

    To fix this you'll need to initialize your state with the default values,

    const INITIAL_STATE = {
        id:0,
        numbers:[]
    }
    
    
    //reducer
    const reducer = (state = INITIAL_STATE, action) => {
    
    // Rest of the code
    

    const INITIAL_STATE = {
        id:0,
        numbers:[]
    }
     
    const good = (state = INITIAL_STATE) => {
      return {
        numbers:[...state.numbers]
      }
    }
    
    console.log(good());