Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

298
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!