Alexander Baltazar
Alexander Baltazar

Reputation: 27

UseReducer change state

Im just making a simple app where the I get a data from api then display its title. On initial render, its working fine but whenever I try to change the value by giving an input(number), it doesnt work. can someone please help me point out whats wrong with my code? TIA Heres the screenshot of my code. https://i.sstatic.net/q47ns.png
https://i.sstatic.net/d1FvV.png

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

const initialState = {
    isLoading : true,
    isError : '',
    id: 1,
    fetchedData : {}    
}

const actionHandler = (state,action) => {
    switch(action.type)
    {       
        case 'success' : 
            return {
                isLoading : false,
                isError : '',
                fetchedData: action.fetchedData
            }
        case 'error': 
            return {
                isLoading : false,
                isError : 'Something went wrong!',
                fetchedData: {}
            }
        case 'change' : 
            return {...initialState, id : action.value}
    }
}

function HooksUseReducerDataFetchingApp()
{
    const [data,action] = useReducer(actionHandler,initialState);
    useEffect(() => {
        axios.get(`https://jsonplaceholder.typicode.com/posts/${data.id}`)
            .then(response => {
                action({type:'success', fetchedData: response.data, error : 1000})                              
            })
            .catch(error => {               
                action({type:'error'})
            })
    }, [data])
    return(
        <>
            {data.isLoading ? 'Loading...' : console.log(data) }
            { data.isError ? data.isError : null }<br />
            <input 
                type="number"
                placeholder = "Enter a number"
                value = {data.id}
                onChange = { (e) => action({type: 'change', value: e.target.value }) }
            />
        </>
    )
}

export default HooksUseReducerDataFetchingApp

Upvotes: 1

Views: 165

Answers (1)

Jagrati
Jagrati

Reputation: 12222

You are passing initialState.id in you axios call. Instead you need to pass data.id as a useEffect dependency and pass it in your axios call.

You need use state value in your actionHandler to get the correct value:

const actionHandler = (state,action) => {
    switch(action.type)
    {       
        case 'success' : 
            return {
                ...state
                isLoading : false,
                isError : '',
                fetchedData: action.fetchedData
            }
        case 'error': 
            return {
                ...state,
                isLoading : false,
                isError : 'Something went wrong!',
                fetchedData: {}
            }
        case 'change' : 
            return {...state, id : action.value}
    }
}

Upvotes: 1

Related Questions