Sambulo Senda
Sambulo Senda

Reputation: 1418

Unhandled Rejection (Error): Given action returned undefined React JS

I am not sure why I get the error. Unhandled Rejection (Error): Given action "SET_CARS", reducer "cars" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.

REDUCERS

  import { SET_CARS} from "../actions";
  import { combineReducer } from "redux";

  function cars(state = [], action) {
  switch (action.type) {
  case SET_CARS:
  return 
  action.items;
  default:
  return state; }
  }

 const rootReducer = combineReducers({
 cars
 });

 export default rootReducer;

ACTIONS

 export const SET_CARS = 'SET_CARS';

 export function setCars(items){
  return {
    type: SET_CARS , 
    items
}
}

SearchCars

class SearchCars extends Component {
 constructor() {
  super();


   this.state = {
  tansmition: ""
  };
  }

search() {
let { tansmition } = this.state;
const url = `http://localhost:4000/vehicles/? 
transmission=${tansmition}`;


fetch(url, {
  method: 'GET'
})
.then(response => response.json())
.then(json => {
    this.props.setCars(json.results)
  })
}

enter image description here

Upvotes: 3

Views: 4223

Answers (2)

kingdaro
kingdaro

Reputation: 11998

ASI strikes again.

return 
action.items;

This gets interpreted as:

return;
action.items;

Put them together on one line and it should work. I'd also consider using a formatter like prettier. It'll help yourself and others looking at your code to see bugs like this more easily.

Upvotes: 2

AndrewL64
AndrewL64

Reputation: 16301

Your fetch is missing a return in it's fat arrow function and thus the fetch is not returning anything.

Change this line:

.then(json => {
    this.props.setCars(json.results)
})

To this:

.then(json => {
    return this.props.setCars(json.results)
})

Upvotes: 1

Related Questions