0
votes

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

2

2 Answers

0
votes

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.

0
votes

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