dagoo
dagoo

Reputation: 93

context state does not update

i am new to context api, I tried updating the context state by sending a dispatch to the reducer, but when i log the state, i get the default state. however when i inspected inside the react dev tools, i found the the state does have a changed state, but it's just not logging it out in the console, am i doing something wrong?

const State = ({ children }) => {
const initState = {
    trending: [],
    search: []
}
const [state, dispatch] = useReducer(Reducer, initState)

useEffect(() => {
    console.log(state.trending) //returns []
    dispatch({ type: 'LOAD_TRENDING', payload: ['some Data'] })
    console.log(state.trending); // returns [] instead of ['some Data']
    },
 [])}

React developer tools inspect screenshot

Upvotes: 1

Views: 142

Answers (1)

Cybershadow
Cybershadow

Reputation: 1167

You need to put state.trending in the dependency array in the useEffect. So your could would look like:

    useEffect(() => {
        console.log(state.trending) //returns []
        console.log(state.trending); // returns [] instead of ['some Data']
      },
    [state.trending]) // this is new
    }

Also moving the dispatch to a seperate useEffect to avoid infinite rendering.

useEffect(() => {
     dispatch({ type: 'LOAD_TRENDING', payload: ['some Data'] })
    },
 [])}

Upvotes: 1

Related Questions