I have been trying to solve the issue below for quite some time but haven’t been able to figure out what is wrong.
I am dispatching an action from my component, and the state is getting updated, as confirmed by logging it in the action. However, when I try to access the value of the state immediately after dispatching the action, it still shows the initial state value.
Please have a look at the below code.
entitySlice.js
export const entitySlice = createSlice({
name: 'entity',
initialState,
reducers: {
setEntity: (state, action) => {
state = action.payload;
console.log(state.entityAttributes);
},
},
});
export const { setEntity } = entitySlice.actions;
export default entitySlice.reducer;
Editor.jsx
const EntityEditor = () => {
const effectRan = useRef(false);
const [searchParams] = useSearchParams();
const dispatch = useDispatch();
const entityData1 = useSelector((state) => state.entity);
useEffect(() => {
if (!effectRan.current) {
effectRan.current = true;
getEntityData();
}
});
const getEntityData = async () => {
entityOperations.getEntity(searchParams.get("PK_Entity")).then(function (response) {
dispatch(setEntity(response));
console.log(entityData1);
},
function (error) {
console.log(error);
}
);
};
}
I am getting the correct response from the API, and the state value is changing as expected when I check it using console.log(state.entityAttributes);
. However, when I check the data using console.log(entityData1);
, I still see the initial state value, not the updated one. Any pointers on how to fix this would be greatly appreciated.
Thanks