0

I've been trying to update state when fetching data from an API using the use reducer hook, but it's not updating even though my API request was successful, and I can see the data. Is there something I'm doing wrong? I've checked my console, and it doesn't give any errors. I've also crosschecked for misspellings

function Provider (props) {
    let trackState = {
        trackList: [],
        heading: "Top 10 Tracks"  
    }

    const reducer = (state, action) => {
        switch (action.type) {
            case "SEARCH TRACKS":
                return {
                   ...state,
                    trackList: action.payload,
                    heading: 'Search results'
                }

            case "NOT_SEARCHING":
                return {
                    ...state,
                    trackList: action.payload,
                    heading: 'TOP 1O Tracks',
                }

            default:
                return state
        }
    }

    const [state, dispatch] = useReducer(reducer, trackState)

    React.useEffect(() => {
fetch(`https://thingproxy.freeboard.io/fetch/${API.url}${API.tracks}&apikey=${API.key}`) 
        .then(res => {
             if(res.ok) { 
                return res.json()
                }  
                else {
                    throw res;
                }
        
            })
            .then(result => {
                
                dispatch({ type: "NOT_SEARCHING", payload: result.message.body.track_list })
                
                console.log(state)
            }
            )
        }, [])  
        

    return (
        <Context.Provider value={{trackState, API, dispatch}}>

          {props.children}
        </Context.Provider>
    )

}

export {Provider, Context}

Ken White
  • 123,280
  • 14
  • 225
  • 444
Abby
  • 1

1 Answers1

0

I think it's all looking fine. You are trying to log the state before it gets updated. Try to log in a different useEffect to see if the state is updated.

React.useEffect(() => {
console.log('State is changed!!',state)
 }, [state]) 

hope this helps!!

Anu
  • 359
  • 4