El error tipográfico en redux-toolkit, “action is not a function”, no es una función.
He buscado en otras publicaciones y parece ser un problema de exportación de nombres, pero he revisado una y otra vez mi código y no puedo entenderlo. Agradeceré cualquier consejo.
Este es el error que estoy obteniendo:
TypeError: (0 , _redux_wetherSlice__WEBPACK_IMPORTED_MODULE_2__.setLocalLatitude) no es una función
en localWether.js:14
Componente “slice”
import { createSlice } from “@reduxjs/toolkit”;
export const wetherSlice = createSlice({
name: “wether”,
initialState: {
localLocation: {
latitude: “”,
longitude: “”,
},
reducers: {
setLocalLatitude: (state, action) => {
state.localLocation.latitude = action.payload;
},
setLocalLongitude: (state, action) => {
state.localLocation.longitude = action.payload;
},
},
},
});
export const { setLocalLongitude, setLocalLatitude } = wetherSlice.actions;
export default wetherSlice.reducer;
Componente “react”
import { useEffect } from “react”;
import { useDispatch, useSelector } from “react-redux”;
import { setLocalLatitude, setLocalLongitude } from “../../redux/wetherSlice”;
const LocalWether = () => {
const dispatch = useDispatch();
const { localLocation } = useSelector((state) => state.wether);
useEffect(() => {
navigator.geolocation.getCurrentPosition((position) => {
try {
console.log(position);
dispatch(setLocalLatitude(position.coords.latitude));
dispatch(setLocalLongitude(position.coords.longitude));
} catch (err) {
console.log(err);
}
});
}, []);
console.log(localLocation);
return ;
};
export default LocalWether;
Almacén “store”
import { configureStore } from “@reduxjs/toolkit”;
import wetherReducer from “../redux/wetherSlice”;
const store = configureStore({
reducer: { wether: wetherReducer },
});
export default store;
davy.ai
El mensaje de error indica que
setLocalLatitude
no es una función. Al examinar el código enwetherSlice.js
, parece que el objetoreducers
está anidado dentro del objetoinitialState
. El objetoreducers
debería moverse fuera deinitialState
, para que se convierta en un hijo directo decreateSlice
. El archivowetherSlice.js
corregido debería verse así:Con este cambio, las funciones
setLocalLatitude
ysetLocalLongitude
deberían estar definidas y funcionar correctamente en el componenteLocalWether
.