samsino
samsino

Reputation: 17

useSelector not firing after change in redux store

I am working on an appication that I am using redux

I want to use useEffect to load data when the page opens and log the data to store

but useSelector does not change when data in store changes

I fetch the data from an api and dispatch it to the redux store and use useSelector the get the dispatched values. the useEffect dispatches the data to the store but useSelector does not pickup the values after the change

Category

 const categorys = useSelector(state => state.category.category)

useEffect(() => {
    setLoading(true)
   
    listCategory()
    .then(res => {
        dispatch({
            type: "LIST_CATEGORIES",
            payload: res.data.data
        })
        setLoading(false)
    })
    .catch(err => {
        if (err.response) {
            // Request made and server responded
            toast.error(err.response.data.error)
            toast.error(err.response.data.name)
            toast.error(err.response.data.email)
            toast.error(err.response.data.password)
            toast.error(err.response.data.username)

          } else if (err.request) {
            // The request was made but no response was received
            console.log(err.request);

          } else {
            // Something happened in setting up the request that triggered an Error
            console.log('Error', err.message);

          }
        setLoading(false)
    })
}, [])

reducer

const initialState = {
    category:[
      
    ],
    current: null

}
export const categoryReducer = (state = initialState, action) =>{
    switch(action.type){
        case "LIST_CATEGORIES":
            return {
                ...state,
                ...action.payload
            };

        default:
            return state
    }
};

Data from api

res.data.data = [{ _id: "ksdj9dsfj", name: "monitor", description: "It is used to view what is on the system" }]

Upvotes: 0

Views: 1948

Answers (1)

markerikson
markerikson

Reputation: 67459

The problem is that your update logic does not match the returned data structure from the API.

Currently, you have this initial state:

const initialState = {
    category:[],
    current: null
}

and this logic in your categoryReducer:

return {
  ...state,
  ..action.payload
}

That logic will only work right if action.payload looks like {category: []}.

But, you showed that the data coming back from the server looks like:

[{ _id: "ksdj9dsfj", name: "monitor", description: "It is used to view what is on the system" }]

That is not an object, and it does not have a category field inside.

One fix here would be to change the reducer logic to look like:

return {
  ...state,
  category: action.payload
}

Upvotes: 1

Related Questions