I have been trying to combine React-hooks, Redux and Typescript. Every time I fix an error, a new one appears.
Can anyone see what the issue seems to be?
Right now I get the following error about my reducer:
Unhandled Rejection (TypeError): action.places is not iterable
Without typescript, this code works. So I should be missing something or doing something wrong type-wise.
// Types
export interface Place {
type: string;
geometry: Geometry;
properties: Properties;
id: number;
}
interface Geometry {
type: string;
coordinates: [number, number];
}
interface Properties {
Id: string;
Title: string;
Url: string;
ImageUrl: string;
Bullets: boolean;
}
export const FETCH_DATA: string = "FETCH_DATA";
export interface FetchDataAction {
type: typeof FETCH_DATA;
places: Place[];
}
export type PlaceActionTypes = FetchDataAction;
export type AppActions = PlaceActionTypes;
// Action
// places = axios.create({baseURL}) (the API is an array of type Place[])
export const fetchPlaces = () => async (dispatch: Dispatch) => {
const response = await places.get(`places`);
dispatch({
type: "FETCH_DATA",
payload: response.data
});
};
// Reducer
export const initialState: Place[] = [];
const placeReducer = (state = initialState, action: PlaceActionTypes) => {
switch (action.type) {
case FETCH_DATA:
return [...state, ...action.places];
default:
return state;
}
};
// Here is my Component
const HomePage = () => {
const places: Place[] = useSelector((state: any) => state.places);
const dispatch = useDispatch();
useEffect(() => {
places.length === 0 && dispatch(fetchPlaces());
});
console.log(places);
return <div>HomePage</div>;
};