I can not access a files array in a component named ‘Files’
Dispatching the Action:
This function handles the change event when a file is selected. It extracts metadata from the file and dispatches an action pushFile with this metadata to add it to the Redux store.
const handleFileChange = (e) => {
const file = e.target.files[0]
if (file) {
const fileMetaData = {
name: file.name,
size: file.size,
type: file.type,
lastModified: file.lastModified
}
dispatch(pushFile(fileMetaData))
// optionally we can upload to server from here ...
}
}
Redux Store Configuration:
This code configures the Redux store using configureStore from Redux Toolkit. It combines reducers, where fileReducer is responsible for managing file-related state.
import { configureStore } from "@reduxjs/toolkit";
import fileReducer from './fileSlice'
const store = configureStore({
reducer: {
fileUpload: fileReducer
}
})
export default store;
File Reducer:
This file defines a slice of the Redux store state for managing files. The pushFile reducer adds a file to the files array in the state.
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
files: []
}
const fileSlice = createSlice({
name: "file",
initialState,
reducers: {
pushFile: (state, action) => {
console.log("Action payload: ", action.payload);
state.files.push(action.payload)
console.log("Updated State:", [...state.files]);
}
}
})
export const { pushFile } = fileSlice.actions
export default fileSlice.reducer
Accessing Files in the Files Component:
This code snippet extracts the files array from the Redux store state using the useSelector hook. It logs changes to the files array using the useEffect hook.
const files = useSelector((state) => state.file?.files || []);
useEffect(() => {
console.log("Files changed:", files);
}, [files]);
Here are the outputs when I try to upload a file:
Output
Issue:
Despite dispatching the pushFile action, the files array in the Files component remains empty or unchanged.
Expected Output:
The files array in the Files component should contain the newly added file metadata after dispatching the pushFile action.