Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't use state.filter in Redux reducer

So I'm using React-Redux and in my reducer I want to remove a hostname from my state. So from looking around I found out state.filter is a good way to achieve this. However, this is not working, I keep getting an error in my console.

index.js

import "babel-polyfill";
import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import thunkMiddleware  from 'redux-thunk';
import createLogger from 'redux-logger'
import { HostnameAppContainer } from './components/HostnameApp';
import {createStore, applyMiddleware} from 'redux';
import hostnameApp from './reducer'
import {fetchHostnames} from './action_creators'

const loggerMiddleware = createLogger()

const store = createStore(
    hostnameApp,
    applyMiddleware(
        thunkMiddleware, // lets us dispatch() functions
        loggerMiddleware // neat middleware that logs actions
    )
)

store.dispatch(fetchHostnames())

ReactDOM.render(
    <Provider store={store}>
        <HostnameAppContainer />
    </Provider>,
document.getElementById('app')
)
;

reducer.js

export default function(state = {hostnames:[]}, action) {
    switch (action.type) {
        case 'FETCH_HOSTNAMES':
            return Object.assign({}, state, {
                hostnames: action.hostnames
            })
        case 'DELETE_HOSTNAME':
            return state.filter(hostname =>
                hostname.id !== action.hostnameId
            )
        case 'ADDED_HOSTNAME':
            return Object.assign({}, state, {
                hostnames: [
                    ...state.hostnames,
                    action.object
                ]
            })
    }
    return state;
}

error

Thankyou in advance for all suggestions or solutions.

like image 908
Matthias Avatar asked Feb 07 '23 04:02

Matthias


1 Answers

In your case 'DELETE_HOSTNAME' you are calling state.filter. Your state at this point will be an Object and not an array.

You will probably want to do something like this:

case 'DELETE_HOSTNAME':
  return { hostnames: state.hostnames.filter(hostname =>
     hostname.id !== action.hostnameId
  )}
like image 71
Clarkie Avatar answered Feb 09 '23 22:02

Clarkie