1

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 :

Argument of type 'InitialStateType' is not assignable to parameter of type 'never'. TS2769


  > 16 | const [state, dispatch] = useReducer(Reducer, initState )
       |                           ^

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 y la verdad no se de donde deduce que el modelo sensor o initial state posee never...

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 
  }

reducer.ts

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

const Reducer = (state: InitialStateType, action: Action) : InitialStateType | Error => {
    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,
            };
        }
        default:
            throw new Error('Error in the change of state');
    }
};

export default Reducer;

ListSensor.tsx

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);
  };

sensorForm.tsx

import { FC, FormEvent , useState } from 'react'
import { SensorForm } from '../../interfaces/interfaces';
import '../../styles/FormSensor.css';
import { InputChange, SelectChange } from '../../types/types';

interface Props {
    event: Function
}
const FormSensors : FC<Props> = (props ) => {

   
     
    const initialState = {
      active: false,
      lat: '',
      lng: '',
      name: "",
    };

    const [sensor, setSensor] = useState<SensorForm>(initialState);

    
    const handleInputChange = (e: InputChange) => {
    setSensor({ ...sensor, [e.target.name]: e.target.value });
    }

    const handleSelectChange = (e: SelectChange) =>{
        console.log('cambie')
        setSensor({ ...sensor, [e.target.name]: e.target.value });
    }

    const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
        e.preventDefault()
        const setObjectSensor = {
            name: sensor.name,
            ubication : [parseInt(sensor.lat), parseInt(sensor.lng)],
            maxVal: parseInt(sensor.lat) < parseInt(sensor.lng) ?  parseInt(sensor.lng) :  parseInt(sensor.lat) ,
            minVal: parseInt(sensor.lat) > parseInt(sensor.lng) ?  parseInt(sensor.lng) :  parseInt(sensor.lat) ,
            active: sensor.active
        }
        props.event(setObjectSensor)
    }

    return (
            <tr>
                    <td>
                        <form onSubmit={handleSubmit} id="my_form">
                            <select onChange={handleSelectChange}   name='active' className='select-status'>
                                <option>none</option>
                                <option  value="true">active</option>
                                <option value="false">inactive</option>
                            </select>
                        </form>
                    </td>
                    <td><input className="input-name" type="text" placeholder="name"  form="my_form" name="name" onChange={handleInputChange}
                    autoFocus/></td>
                    <td><div className="div-ubication"><input  name="lat" className="input-lat" type="text" placeholder="-90 to 90" form="my_form"  onChange={handleInputChange}
                    autoFocus />° lat</div>
                    <input className="input-lng" type="text" name="lng" placeholder="-180 to 180" form="my_form"  onChange={handleInputChange}
                    autoFocus/>° lng</td>
                    <td>-</td>
                    <td>-</td>
                    <td>-</td>
                    <td>
                        <button className="button button-create" type="submit" form="my_form">
                            <i className="material-icons">
                                add_circle_outline
                            </i>
                        </button>
                        <button className="button button-clear">
                            <i className="material-icons">
                                clear
                            </i>
                        </button>
                    </td>            
            </tr>
    )
}

export default FormSensors;

desde el back poseeo estos controladores con su respectivas retornaciones

sensorController.ts

import { RequestHandler } from "express";
import Sensor from '../models/sensor';

export const createSensor: RequestHandler =  async(req, res) =>{
  try{
    const sensorFound =  await Sensor.findOne({name: req.body.name})
    if(sensorFound){
    return res.status(301).json({message: 'The sensor name is busy, change the name'})
  }
    const sensor =  new Sensor(req.body)
    const saveSensor = await sensor.save()
    res.json(saveSensor)
}catch (err){
  return res.status(404).send(err)
}
}


export const getSensors: RequestHandler = async (req, res) =>{
  try {
      const sensors = await Sensor.find();
      return res.json(sensors)
  } catch (err) {
      return res.status(404).json(err)
  }
};


export const deleteSensor: RequestHandler = async (req, res) =>{
  try{
  const sensorFound = await Sensor.findByIdAndDelete(req.params.id)
if(!sensorFound){
  return res.status(204).json({message : 'Sensor not found'});
}
  return res.json(sensorFound)
}catch (err){
  return res.status(404).json(err)
}
}


export const updateSensor: RequestHandler = async(req, res) =>{
  try{
const sensorUpdate =  await Sensor.findByIdAndUpdate(req.params.id, req.body, {new : true})
if(!sensorUpdate)   return res.status(204).json({message : 'sensor not update'});
return res.json(sensorUpdate);
}catch (err){
  return res.status(404).json(err)
}
}

alguien podria guiarme

2
  • Estaría bien que pudieras comprobar el tipo de useReducer (por ejemplo, si tu IDE muestra el tipo al pasar el cursor por encima). Quizás el problema venga de que Reducer tiene indicado como posible valor de retorno Error, cuando en realidad en ningún caso devuelve ese tipo (puede generar una excepción, que no es lo mismo). Así que ningún valor de initState en useReducer nos puede garantizar que el primer valor retornado por ese hook sea un estado válido. Commented el 20 sept. 2021 a las 17:35
  • Si pudieras confirmar que las respuesta a tu pregunta anterior te funcionaron, ya que parece haber relación entre esta pregunta y la anterior.
    – g.4
    Commented el 20 sept. 2021 a las 20:24

0

Tu Respuesta

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

Examina otras preguntas con la etiqueta o formula tu propia pregunta.