Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

300
Vistas
React js useReducer hook in forms controlled inputs

I'm having issues with using useReducer with input. I'm trying to use controlled input here but I keep getting errors; Controlled input is uncontrolled

import React, {useReducer, useEffect} from "react";

import axios from "axios";

const initialState = {

post: {},

user: ""

} const reducer = (state, action) => {

switch(action.type){

    case "Fetch_data":

        return {

            post: action.payload

        }

    case "On_change":

        return {

            user: action.payload

        }    

    case "Fetch_error":

        return {

            post: {}

        } 

    default:

        return state  
 
}

} const ReducerFetchdata = () => {

const [info, dispatch] = useReducer(reducer, initialState)

useEffect(()=>{

    axios

        .get(`https://jsonplaceholder.typicode.com/posts/${info.user}`)

        .then (res => {

            console.log(res)

            dispatch({type: "Fetch_data", payload: res.data})

        })

        .catch(err => {

            console.log(err)

            dispatch({type: "Fetch_error"})

        })

}, [info.user])

const handleChange = (event) =>{

    dispatch({type: "On_change", payload: event.target.value})

}

return(

    <div>

        <input type="text" onChange={handleChange} value={info.user}/>

        <p>{info.post.title}</p>

    </div>

)

}

export default ReducerFetchdata

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Just a guess: you are removing your user key after you fetch your post, so info.user becomes undefined.

Your reducer should be:

switch(action.type) {
  case 'Fetch_data':
    return {
       ...state,
       post: action.payload
    }
   ...
}

Always return

{
   ...state
   [someKey]: someValue
}

in your On_Change and Fetch_error as well.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You need to spread whole state and then update the necessary key when returning from the reducer. In this case onChange called On_change whose action did not return post from reducer state and thus causing error.

Refer : Sandbox for the fix

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda