4

estoy teniendo un problema de tipo con typescript en donde al trabajar con el hook de react useReducer la consola me tira el siguiente error :

Function lacks ending return statement and return type does not include 'undefined'. TS2366

5 | const Reducer = (state: InitialStateType, action: Action): InitialStateType => {

he intentado asignarle tipo al valor que devuelve el handle del submit antes de hacer las acctions, no es ese el problema parece venir vinculado a mis services o mi reducer la verdad me gustaria que pudieran guiarme...

reducerSensor.ts

import { InitialStateType } from "../interfaces/interfaces"
import { Action } from "../types/types";

const Reducer = (state: InitialStateType, action: Action) : InitialStateType => {
    switch (action.type) {
        case 'REQUEST_GET': {
            return {
                ...state,
                loading: true,
            };
        }
        case 'SUCCESS_GET': {
            return {
                ...state,
                loading: false,
                sensors: state.sensors.concat(action.payload)
            };
        }
        case 'ERROR_GET': {
            return {
                ...state,
                loading: false,
                error: action.error,
            };
        } 
        case 'REQUEST_CREATE' : {
            return {
                ...state,
                loading: true,
            };
        }
        case 'SUCCESS_CREATE' : {
            return {
                ...state,
                loading: false,
                sensors: [...state.sensors, action.payload]
            };
        }
        case 'ERROR_CREATE': {
            return {
                ...state,
                loading: false,
                error: action.error,
            };
        }
    }
};

export default Reducer; `

ListSensor

import { FC ,useEffect , useReducer} from 'react'
import '../../styles/ListSensors.css'
import FormSensors from '../FormSensors/FormSensors'
import * as sensorServices from '../../services/sensorServices'
import Reducer from '../../Reducers/reducerSensor'
import { InitialStateType, Sensor } from '../../interfaces/interfaces'

const ListSensors: FC<HTMLDataListElement>= () => {

const initState: InitialStateType = {
    sensors: [],
    loading: true,
    error: false
}

const [state, dispatch] = useReducer(Reducer, initState )

const { sensors, loading, error } = state;

useEffect(() => {
    dispatch({ type: 'REQUEST_GET' });
    const loadSensors = async () => {
        const res = await sensorServices.getSensors();
        if (res.status === 200) {
            dispatch({ type: 'SUCCESS_GET', payload: res.data });
            return;
        }
        dispatch({ type: 'ERROR_GET', error: res.data});
    };
    loadSensors();
}, []);

const handleCreate = (objectSensor : Sensor)  => {
    dispatch({ type: 'REQUEST_CREATE' });
        const createSensor = async () => {
            const res = await sensorServices.createNewSensor(objectSensor);
            if (res.status === 200) {
                dispatch({ type: 'SUCCESS_CREATE', payload: res.data });
                return;
            }
    dispatch({ type: 'ERROR_CREATE', error: res.data});
        };
   createSensor();
}

    return (
        <div>
             {loading ? (
                <p>loading...</p>
            ) : error ? (
                <p>{error}</p>
            ) : (
            <div className='datatable-container'>
                <table className="datatable">
                    <thead>
                        <tr>
                            <th>Status</th>
                            <th>Name</th>
                            <th>Ubication (lat / lng)</th>
                            <th>MinVal</th>
                            <th>MaxVal</th>
                            <th>Events</th>
                            <th>Options</th>         
                        </tr>
                    </thead>
                    <tbody>
                        <FormSensors  event={handleCreate}/>     
                        {
                            sensors && sensors.length > 0 ? sensors.map((sensor: Sensor) => (
                                <tr key={sensor._id}>
                                    <td><span className={sensor.active ? "active" : "inactive"}></span></td>
                                    <td>{sensor.name}</td>
                                    <td>{sensor.ubication[0]}° lat , {sensor.ubication[1]}° lng</td>
                                    <td>{sensor.minVal}°</td>
                                    <td>{sensor.maxVal}°</td>
                                    <td><button  className="button button-event"><i className="material-icons">sensors</i></button></td>
                                    <td> <button className="button button-delete"><i className="material-icons">delete</i></button> <button className="button button-update"><i className="material-icons">edit</i></button></td>   
                                </tr>
                            )
                          )  : null
                        }
                    </tbody>
                </table>
            </div>
            )}
    </div>
    )
}

export default ListSensors

SensorServices.ts

import axios from "axios";
import { Sensor } from "../interfaces/interfaces";

const API = "http://localhost:3001";

export const getSensors = async () => {
  return await axios.get(`${API}/sensors`);
};

export const createNewSensor = async (sensor: Sensor) => {
    return await axios.post(`${API}/sensor`, sensor);
  };
  
  export const deleteSensorById = async (id: string) => {
    return await axios.delete(`${API}/sensors/${id}`);
  };
  
  export const updateSensor = async (id: string, sensor: Sensor) => {
    return await axios.put(`${API}/sensors/${id}`, sensor);
  };

types.ts

import { ChangeEvent } from 'react';
import { Sensor } from '../interfaces/interfaces';

export type Action =
    { type: 'REQUEST_GET'}
|   { type: 'SUCCESS_GET', payload: Sensor }
|   { type: 'ERROR_GET' , error: string }
|   { type: 'ERROR_CREATE' , error: string }
|   { type: 'REQUEST_CREATE' }
|   { type: 'SUCCESS_CREATE', payload: Sensor }

export type InputChange = ChangeEvent<HTMLInputElement | HTMLTextAreaElement>;

export type SelectChange = ChangeEvent<HTMLSelectElement >

interfaces.ts


export interface Sensor {
    _id?: string;
    name: string;
    ubication: number[]
    maxVal: number;
    minVal: number;
    active: boolean;
    createdAt?: string | Date;
    updatedAt?: string | Date;
  }

  export interface  SensorForm {
    name: string;
    lat: string;
    lng: string;
    active: boolean;
  }
  export interface InitialStateType  {
    sensors: Sensor[],
    loading: Boolean,
    error: Boolean | String 
  }
``````
1
  • un "return state" al final faltaría el 20 sep. 2021 a las 16:26

2 respuestas 2

1

Es porque le estas indicando que SI O SI retorne un InitialState. Pero a esa funcion, sea el caso que le pasas un ACTION_TYPE que no corresponde con ninguna opcion del switch, te de undefined.

(Deberias ponerle un default state por ejemplo)

Yo diria que es por esto. Saludos!

1

El reducer debe devolver un state siempre, no solo cuando concuerda con uno de los actions, deberías agregarle un default case al switch así:

default: {
  return state;
}

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.