React-redux does not re-render on state change

Viewed 113

I just started with redux and react-redux. I am observing a very weird behavior and not able to wrap my head around it.

I am trying something like this.

const fetchedFolders = useSelector(state=>{
        console.log("redux state = ",state);
        return state.fetchedFolders;
    });

const updateFetchedFolders = useDispatch();

I have callback function that receives a new set of values and will update the state in store.

let appendFoldersToList=(newFolders)=>{
        console.log(typeof(newFolders))
        if(typeof(newFolders) === undefined)
            console.log("go to error");
        
        else{
            updateFetchedFolders(setFetchedFolders([...fetchedFolders,...newFolders]));
        }
    }

this works perfectly and re-renders the list with new value but if I replace the line

updateFetchedFolders(setFetchedFolders([...fetchedFolders,...newFolders]));

with

updateFetchedFolders(setFetchedFolders([...newFolders]));

it does not re-render and it still shows the old list. but in console, I can see data is updated.

I am not able to understand why it re-renders in first case and not in second case.

This is how my reducers look:-

export const reducer = (state=initialState, action)=>{

    switch(action.type){
        case 'SET_FOLDERS': return {
            ...state,
            fetchedFolders:[...action.payload]
        }
    }
}

this is my action creator:-

export const setFetchedFolders = (payload)=>{
    return {
        type:'SET_FOLDERS',
        payload:payload
    }
}

this is my initial state:-

const initialState = {
    fetchedFolders:[],
    
}

I don't think I am not mutating the state.

my array looks something like this::-

[
   {name:cats, id:SOME_ID},
   {name:dogs, id:SOME_ID}
]
0 Answers
Related